简体   繁体   中英

Update request in CRUD function

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

For the Update request, I tried this piece of code for my application "Small",

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 am unable to understand the significance and role of criteria array and the second argument for update function

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

I got it that criteria will be specifying the changes we want to update, but how ?

Somebody please help me out to get a better understanding of this.

First of all criteria is not an array but it is an empty object .

As of What I see in the code the line

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

The Above line signifies that you are merging the conditions sent in an as both parameters in the URL and body of the post command using lodash into an object.

req.params.all() gives you the collection of parameters culled from (in order of precedence):

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

According to Sails Documentation Update is an ORM Command which Updates existing records in the database that match the specified criteria. I have created a sample example where I take the _id from the body of the post command. The Criteria over here is the column that 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM