Mongoose: findOneAndUpdate doesn’t return updated document

Mongoose: findOneAndUpdate doesn’t return updated document

Asked on January 2, 2019 in MongoDB.
Add Comment


  • 3 Answer(s)

    The original, unaltered document is return from default. If we need a new, latest document to be returned you have to pass an additional argument: an object with the new property set to true.

    Through from 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`
    });
    

    Here, Option

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

     

    Then, if we need the latest answer in doc variable:

    Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}}, {new: true}, (err, doc) => {
         if (err) {
                console.log("Something wrong when updating data!");
         }
         console.log(doc);
    });
    
    Answered on January 2, 2019.
    Add Comment

    When you  using the Node.js driver instead of Mongoose, You will need to use {returnOriginal:false} instead of {new:true}

    Answered on January 2, 2019.
    Add Comment

    The original document return from by default findOneAndUpdate. If you want it to return the modified document pass an options object { new: true } to the function:

    Cat.findOneAndUpdate({ age: 17 }, { $set: { name: "Naomi" } }, { new: true }, function(err, doc) {
    });
    
    Answered on January 2, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.