I am using SailsJS for a project and I need to use native()
for specific requests. The problem is that I cannot find the correct way to instantiate the Waterline model object from the result of the mongo collection find
. I was looking for information about this, and the only thing I found was the following:
var instance = new Model._model(mongo_result_item);
This should work correctly, but when I do instance.save(function(err, ins){});
, the model throws an error due to the "_id" field, which should be "id".
I looked at the Mongo sail code and I found that for the find method they do this:
collection.find(where, query.select, queryOptions).toArray(function(err, docs) {
if(err) return cb(err);
cb(null, utils.normalizeResults(docs, self.schema));
});
So, normalizeResults does the magic with the _id attribute and other things.
, , - , sails-mongo utils.js .
:
var mongoUtils = require('sails-mongo/lib/utils.js');
SampleModel.native(function(nativeErr, collection){
collection.find({ 'field' : value }).toArray(function(collectionErr, results){
if (!results || results.length == 0) return res.restfullInvalidFieldValue({ msg : 'INVALID_VALUE' });
var norm_results = mongoUtils.normalizeResults(results);
var instance = new SampleModel._model(norm_results[0]);
});
});
/ ?
, Waterline find(), , . :/^ {string} $/i
, , . , {field: {$ regex: new RegExp ('^' + regexp_escaped_string + '$')}} , , , {field: value}.
- , , .
.