How to properly create an instance of a Waterline model object using my own sails-mongo result?

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:

// Run Normal Query on collection
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}.

- , , .

.

+4
1

$regex , , paramteter "i", $regex mongodb.

/**
 * PetController
 *
 * @description :: Server-side logic for managing pets
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */

module.exports = {
    searchByName: function (req,res) {

        Pet
        .native(function(err, collection) {
          if (err) return res.serverError(err);

            collection.find(
            { 
                name: { $regex: /like-my-name/, $options: "i" } // here option "i" defines case insensitive
            }, 
            {
                name: true
            })
            .toArray(function (err, results) {
                if (err) return res.serverError(err);

                return res.ok(results);
            });
        });
  }
};
0

Source: https://habr.com/ru/post/1611584/


All Articles