Unable To Update Mongoose Model
Solution 1:
When you modify the contents of an untyped Array
field like variations
, you need to notify Mongoose that you've changed its value by calling markModified(path)
on the modified document or a subsequent save()
call won't save it. See docs.
for(var i = p.variations.length - 1; i >=0; i--) {
p.variations[i]['color'] = 'red';
}
p.markModified('variations');
p.save(function(err) { ...
Solution 2:
You have to use the set function to change a property. The reasoning behind that is that mongoose has to mark the field as modified in order to be saved to the database.
for(var i = p.variations.length - 1; i >=0; i--) {
p.variations[i].set({"color":"red", "code":"herr"});
// or
p.variations[i].set("color":"red");
p.variations[i].set("code":"herr");
}
An alternative would be to change the field's value the old way, without going trought the setter, then manually mark it as modified: p.markModified('variations');
In my opinion you should always use the setter since this is more readable. You can just pass a json object containing all your changes in parameter and it will safely update the fields that you really want to change.
Post a Comment for "Unable To Update Mongoose Model"