I want to understand what the correct way to update a model instance is, using mongoose, ie:
Having:
User = {
username: {
type: String,
indexed: true
},
email: {
type: String,
indexed: true
},
name: String,
.........
};
I'm sending the whole form through ajax to a controller.
So far, i know of two options:
app.put('/users/', function(req, res){
var id = ObjectId(req.body._id);
User.findOne({_id: id}, function(err, user){
user.name = req.body.name;
....
....
user.save();
});
});
or:
app.put('/users/', function(req, res){
var id = ObjectId(req.body._id);
delete req.body._id
User.update({_id: id}, req.body, function(err){
.....
};
});
Both ways have disadvantages:
In the first approach i have to map all properties one by one;
In the second approach i have to delete all properties that can't be changed;
there is a third possible approach that would make me send from client-side, only the changed properties, but i think that would be a big hassle to.
Is there a good, standardized way that i'm not seeing, to do this?
Thanks
This is the approach I typically use, it involves a small npm package called mongoose-mass-assignement:
https://github.com/bhelx/mongoose-mass-assignment
The docs are pretty self explanatory, easy to use. It basically does the delete for you. So you add protected:true to your model, and then it deletes those properties for you. I like this approach because it still allows me to use the req.body as is. You can use this for updates and inserts as well.
A variant of the first approach is to use underscore's extend method to apply all properties of the body to your model instance:
app.put('/users/', function(req, res){
var id = ObjectId(req.body._id);
User.findOne({_id: id}, function(err, user){
_.extend(user, req.body);
user.save();
});
});
However, be sure to delete any properties you don't want the user to be able to set from req.body first.