Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sails.js: how to update model

Forgive my noob question. I'm using angularjs to send a user model (json) with varying fields. It works well with sails.js default PUT. I overrode the PUT, the problem is that I wish to update the model with the received JSON and do some processing on the modified model. Now I can't update the model with

User.update({
id: req.body.id
},{
req.body
}, function(err, users) {
// Error handling
if (err) {
return console.log(err);
// Updated users successfully!
 } else {
console.log("Users updated:", users);
}
});

Please help

EDIT: After knocking my head on the wall for days, problem solved! I know, my code formatting here is not the best..

changed this:

{
   req.body
  }

to just:

req.body

(without the braces)

full snippet becomes:

User.update({
 id: req.body.id
},
req.body
, function(err, users) {
// Error handling
if (err) {
return console.log(err);
// Updated users successfully!
} else {
console.log("Users updated:", users);
}
 });

Thanks.

like image 338
Stone Cold Avatar asked Sep 13 '13 20:09

Stone Cold


1 Answers

So you figured out your problem, sort of. req.body is already an object. But you really should sanitize it before you put it into your update and then save the object. There's a lot of reasons for this but with Mongo when you get only a partial object you'll replace the object in the collection which, in your example with a user, could be bad. When I send users to the frontend I cull off things I don't want transmitted all over like passwords. The other reason is the golden rule of web application development - never trust the client! I'd start with something like:

var user = User.findOne(req.body.id).done(function(error, user) {
    if(error) {
        // do something with the error.
    }

    if(req.body.email) {
        // validate whether the email address is valid?

        // Then save it to the object.
        user.email = req.body.email;
    }
    // Repeat for each eligible attribute, etc.

    user.save(function(error) {
        if(error) {
            // do something with the error.
        } else {
            // value saved!
            req.send(user);
        }
    });
});
like image 192
sfb Avatar answered Sep 18 '22 21:09

sfb