Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose findByIdAndUpdate() or update() and increment(). How to increment __v?

Is there the way to combine Model.findByIdAndUpdate and Model.increment() which increments mongoose native versionKey? Or Model.update() and any incrementation of __v?

This code doesn't increment __v

Station.update({ _id: req.params.id }, 
               { $set: req.body, $inc: { __v: 1 } }, 
               { multi: false },  callback);

but increments any custom Number field:

Station.update({ _id: req.params.id }, 
               { $set: req.body, $inc: { count: 1 } }, 
               { multi: false },  callback);

So far I've found only one way to increment __v:

Station.findById(req.params.id, function (err, station) {
    station.increment();  // this increments __v
    station.save(req.body, callback)
})
like image 448
Maxim Ponomarev Avatar asked Oct 06 '22 12:10

Maxim Ponomarev


1 Answers

It's possible that this is by design. In particular __v is a special mongoose internal key whose specific use is to prevent multiple save operations from colliding when an Array element of the document has positional changes. Atomic update operations by themselves aren't exposed to this risk, so in isolation they don't need to increment __v.

However it is possible to interleave atomic updates with the non atomic find/save constructs, so I submitted an issue for the developer to look at.

like image 179
mjhm Avatar answered Oct 10 '22 01:10

mjhm