Cartesius00
Cartesius00

Reputation: 24414

Mongoose and findAndModify

I use node.js with mongoose plugin. All I need is to try to select a single document with a query like:

{
  _id: '52261c53daa9d6b74e00000c',
  someAdditionalFlag: 156
}

and if and only if it succeeds then change that flag to another value. Moreover, find and modify operation needs to be atomic. Please, how to achieve that using Mongoose?

Upvotes: 1

Views: 2310

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312149

You don't need to use findAndModify for this as you don't need the original document. So you can just use update like this:

MyModel.update({
  _id: '52261c53daa9d6b74e00000c',
  someAdditionalFlag: 156
}, {
  $set: {someAdditionalFlag: newValue }
},
function(err, numAffected) { ... });

In the callback, numAffected will be 1 if a change was made, otherwise 0.

Upvotes: 3

Related Questions