Maria
Maria

Reputation: 3525

Mongoose: how to check if document is modified via model.findOneAndUpdate()

In mongoose, we can check if an update operation has modified the document with model.update():

model.update(query, update, function(err, raw){
    if (raw.nModified >= 1) console.log('document is modified!')
});

Is there a way to do the same with model.findOneAndUpdate()?

model.findOneAndUpdate(query, update, { new: true }, function(err, doc){
    if (doc) {
        // So MongoDB found the document, but is there a way 
        // to know the document was indeed modified?
    }
});

Upvotes: 6

Views: 5567

Answers (1)

saintedlama
saintedlama

Reputation: 6898

You can pass the option { passRawResult : true } to mongoose to advice mongoose to pass the raw result of the underlying mongodb driver, in this case mongodb-native, as a third argument to the callback.

mongodb-native documentation for findOneAndUpdate

model.findOneAndUpdate(query, update, { new: true, passRawResult : true }, function(err, doc, res){
    // res will look like
    // { value: { _id: 56a9fc80a7f9a4d41c344852, name: 'hugo updated', __v: 0 },
    //   lastErrorObject: { updatedExisting: true, n: 1 },
    //   ok: 1 }
});

In case the update did not succeed due to no matching document was found a null res will be passed to the callback. In case a document matched but field values where the same as before the update res object will not give you enough information to figure out if values were updated for the matching document.

Upvotes: 4

Related Questions