Saturday, 15 September 2012

node.js - Updating a model instance -



node.js - Updating a model instance -

i want understand right way update model instance is, using mongoose, ie:

having:

user = { username: { type: string, indexed: true }, email: { type: string, indexed: true }, name: string, ......... };

i'm sending whole form through ajax controller. far, know of 2 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 first approach have map properties 1 one; in sec approach have delete properties can't changed; there 3rd possible approach create me send client-side, changed properties, think big hassle to.

is there good, standardized way i'm not seeing, this?

thanks

this approach typically use, involves little npm bundle called mongoose-mass-assignement:

https://github.com/bhelx/mongoose-mass-assignment

the docs pretty self explanatory, easy use. delete you. add together protected:true model, , deletes properties you. approach because still allows me utilize req.body is. can utilize updates , inserts well.

node.js mongodb mongoose

No comments:

Post a Comment