mongodb - mongoose won't update object field -


i new moogoose, running difficult update object in db.

here shcema.

var formschema = new schema({   formcontent : {     type : object,     required : true   },    formname : string,   createddatetime : date }); 

here controller update field, have used '[]' , works clean field, whenever put new object , try replace, , stay same... idea or suggestion appreciated. stuck in hrs...

// updates existing form in db. exports.update = function(req, res) {   if(req.body._id) { delete req.body._id; }   form.findbyid(req.params.id, function (err, form) {     if (err) { return handleerror(res, err); }     if(!form) { return res.send(404); }     var updated = _.merge(form, req.body);     // updated.formcontent = [];     updated.save(function (err) {       if (err) { return handleerror(res, err); }       return res.json(200, form);     });   }); }; 

try using _.extend or _.assign instead:

var updated = _.assign(form, req.body); 

this answer shitalshah highlights differences between merge , extend:

here's how extend/assign works: each property in source, copy value as-is destination. if property values objects, there no recursive traversal of properties. entire object taken source , set in destination.

here's how merge works: each property in source, check if property object itself. if go down recursively , try map child object properties source destination. merge object hierarchy source destination. while extend/assign, it's simple 1 level copy of properties source destination.

jsbin illustrate differences.

exports.update = function(req, res) {   if(req.body._id) { delete req.body._id; }   form.findbyid(req.params.id, function (err, form) {     if (err) { return handleerror(res, err); }     if(!form) { return res.send(404); }     var updated = _.assign(form, req.body);     // updated.formcontent = [];     updated.save(function (err) {       if (err) { return handleerror(res, err); }       return res.json(200, form);     });   }); }; 

Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -