Last Updated: February 25, 2016
· thomaspeklak

Mongoose's update does not behave like mongo's update

MongooseJs has in my opinion a great design flaw. They decided to make the live of noobs easier by modifing the behaviour of the model update method in a way that it does not lead to the expected results when you are used to the native driver.

model.update(finderObject, replaceWithObject);

will not replace the found entry with the replaceWithObject, because Mongoose implicitly wraps the replaceWithObject in a $set like this:

model.update(finderObject, {$set : replaceWithObject);

This helps new users to not make stupid things but Mongoose provides no other method to achieve mongo native's behaviour.

Alas, there is a workaround: You can rather simply grab the models collection which is the collection of the mongo native driver that lies beneath mongoose and run the update command there.

model.collection.update(finderObject, replaceWithObject)

The really bad thing is, that this behaviour is only mentioned in a side note in the documentation.

2 Responses
Add your response

Sounds like the Mongoose documentation could be improved regarding this. Have you submitted a doc-path to Mongoose with a suggested update?

over 1 year ago ·

The behaviour is documented, but not very well. Feel free to update it.

over 1 year ago ·