Update request in CRUD function

I am new to Sails and trying to learn CRUD functions to make my first api, using the Ponzi Coder tutorials, How to create a nice json CRUD api in sails from scratch?

For Refresh Request I tried this piece of code for my "Small" application,

module.exports = {

    update: function (req, res, next) {
        var criteria = {};
        criteria = _.merge({}, req.params.all(), req.body);
        var id = req.param('id');
        if (!id) {
            return res.badRequest('No id provided.');
        }
        small.update(id, criteria, function (err, small) {
            if (err) return next(err);
            if (small.length == 0) return res.notFound();
            res.json(small);
        });
    }

} 

      

but I cannot understand the meaning and role of the criteria array and the second argument to the update function

small.update(id, criteria, function (err, small) {...});

      

I realized that the criteria will determine the changes that we want to update, but how?

Someone please help me to understand this better.

+3


source to share


1 answer


First of all, the criterion is not an array , but an empty object .

As for what I see in the code, the line

criteria = _.merge ({}, req.params.all (), req.body);

The line "Above" means that you are concatenating the conditions sent as both parameters in the url and in the tere of the post command using lodash into an object.

req.params.all () gives you a set of parameters, fetched from (in order of precedence):



1.route (e.g. id in / post /: id).
2.the request body 3.query
string

According to Sails Documentation, Update is an ORM command that updates existing records in the database that match the specified criteria. I created an example where I take the _id from the body of the post command. The criteria here is the column you are going to update for that particular ID.

CRUD.update(id,criteria,function(err,sleep){
       if(sleep.length == 0) return res.badRequest();
       if(err) return res.badRequest(err);
       res.json(sleep);
    });
 },

      

Hope this answers your question.

+1


source







All Articles