Mongoose: findOneAndUpdate doesn't return updated document Mongoose: findOneAndUpdate doesn't return updated document mongoose mongoose

Mongoose: findOneAndUpdate doesn't return updated document


Why this happens?

The default is to return the original, unaltered document. If you want the new, updated document to be returned you have to pass an additional argument: an object with the new property set to true.

From the mongoose docs:

Query#findOneAndUpdate

Model.findOneAndUpdate(conditions, update, options, (error, doc) => {  // error: any errors that occurred  // doc: the document before updates are applied if `new: false`, or after updates if `new = true`});

Available options

  • new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)

Solution

Pass {new: true} if you want the updated result in the doc variable:

//                                                         V--- THIS WAS ADDEDCat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}}, {new: true}, (err, doc) => {    if (err) {        console.log("Something wrong when updating data!");    }    console.log(doc);});


For anyone using the Node.js driver instead of Mongoose, you'll want to use {returnOriginal:false} instead of {new:true}.


So, "findOneAndUpdate" requires an option to return original document. And, the option is:

MongoDB shell

{returnNewDocument: true}

Ref: https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

Mongoose

{new: true}

Ref: http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate

Node.js MongoDB Driver API:

{returnOriginal: false}

Ref: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#findOneAndUpdate