zsv-oa
Last Updated: February 25, 2016
·
2.124K
· superboum
Avatar1

Update a model with Mongoose

Problem

You might want update a model with Mongoose, and you have to do it with .save() if you want your hooks used.

But you can have a strange behaviour, where Mongoose will try to insert a model instead of updating it.

Solution : myObject.isNew = false

It doesn't seem to be documented, but you just have to set .isNew property of your object to false.

Example

var Cat = mongoose.model('Cat', { 
  name: String 
});

var kitty = new Cat({
  _id: xxxxx, 
  name: String
});

kitty.isNew = false;
kitty.save();

Source

http://stackoverflow.com/questions/29475118/mongoose-mongodb-throwing-duplicate-key-error-on-save#tab-top

Say Thanks
Respond

2 Responses
Add your response

22030
Morton 066e

Interesting, I can't imagine a time when I'd create a new model in order to update an existing record, rather than using something like Cat.findOneAndUpdate({ _id: xxxxx }) but this is a clever loophole if I ever find a need.

Thanks for sharing.

over 1 year ago ·
22031
Avatar1

If you want to update, using Mongoose validator, without finding it, or when you find an object and populate it, change the populated object and want to save the modification at the same time of the main object, with a pre save.

over 1 year ago ·