In Mongoose (mongodb node.js), how to update existing values ​​and insert missing values ​​without deleting unspecified values?

I am trying to save an instant block of statistics, for example.

model = { id: 123, stats: { fooCount: 117, barCount: 175, bazCount: 654 } } 

... and be able to update an existing record, but only specify new values, for example:

 model.update({ '_id': 123, stats: { fooCount: 118 } }); 

... without resetting the old values ​​in stats . Is this possible if you do not write too much code around my updates?

+4
source share
1 answer

You should use the $ set operator in your update like this:

 var conditions = { _id: 123 }; var update = { $set: { fooCount: 118 }}; var options = { upsert: true }; model.update(conditions, update, options, callback); 

There are many more operators that will be interesting on this MongoDB page.

+6
source

Source: https://habr.com/ru/post/1403777/


All Articles