Dreams
Dreams

Reputation: 8506

Mongoose: findOneAndUpdate doesn't return updated document

Below is my code

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

var Cat = mongoose.model('Cat', {
    name: String,
    age: {type: Number, default: 20},
    create: {type: Date, default: Date.now} 
});

Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}},function(err, doc){
    if(err){
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});

I already have some record in my mongo database and I would like to run this code to update name for which age is 17 and then print result out in the end of code.

However, why I still get same result from console(not the modified name) but when I go to mongo db command line and type "db.cats.find();". The result came with modified name.

Then I go back to run this code again and the result is modified.

My question is: If the data was modified, then why I still got original data at first time when console.log it.

Upvotes: 438

Views: 476287

Answers (17)

Alon Rosenfeld
Alon Rosenfeld

Reputation: 1469

In version "mongodb": "^6.3.0", work with the FindOneAndUpdateOptions options, use {includeResultMetadata: boolean}

/**
 * Return the ModifyResult instead of the modified document. Defaults to true
 * but will default to false in the next major version.
 */
includeResultMetadata?: boolean;

Upvotes: 0

Kamen Kanchev
Kamen Kanchev

Reputation: 49

Make sure you check if you're using Mongoose or MongoDB

if using Mongoose - use {new: true}

const query = await Model.findOneAndUpdate({filter}, {update}, {new: true});

if using MongoDB - use {returnNewDocument: true}

const query = await Model.findOneAndUpdate({filter}, {update}, {returnNewDocument: true});

Make sure you're using the correct one since, because if you don't, it's just gonna get ommited and you're get the old document.

Upvotes: 3

Mohiuddin Saifullah
Mohiuddin Saifullah

Reputation: 11

const updatedDocument = await Model.findOneAndUpdate(req.params.id, req.body, {
    upsert: true,
    new: true,
  })

use this to get update document

Upvotes: 1

Zehan Khan
Zehan Khan

Reputation: 21

This option is necessary to get updated document instance

{ new: true }

Upvotes: 0

All2Pie
All2Pie

Reputation: 360

export function newDocumentOnUpdatePlugin(schema) {
  schema.pre(
    ['update', 'findOneAndUpdate', 'updateOne', 'updateMany'],
    function (next) {
      this.setOptions({ new: true });
      next();
    },
  );
}

I have created this plugin if anyone need this functionality across the whole app and want to avoid repetition. Just use this as a global plugin

Upvotes: 0

Tsuneo Yoshioka
Tsuneo Yoshioka

Reputation: 7874

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}

2021 - Mongodb ^4.2.0 Update
{ returnDocument: 'after' }

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

Upvotes: 105

Pedro Hoehl Carvalho
Pedro Hoehl Carvalho

Reputation: 2433

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

2021 - Mongodb ^4.2.0 Update
{ returnDocument: 'after' }

Upvotes: 164

Crucial
Crucial

Reputation: 41

2021 - Mongodb ^4.2.0 Update

This applies to the mongodb node driver, NOT mongoose.

It seems like the latest version of the Mongodb node driver uses the following syntax, if you are searching and updating using "collection.findOneAndUpdate":

.findOneAndUpdate(query, update, { returnDocument: 'after' | 'before' })

Couldn't find the answer here myself while searching, so posting this in case others are in the same situation.

Upvotes: 3

Prakash Harvani
Prakash Harvani

Reputation: 1041

In some scenarios {new: true} is not working. Then you can try this.

{'returnNewDocument':true}

Upvotes: 1

Aljohn Yamaro
Aljohn Yamaro

Reputation: 2881

I know, I am already late but let me add my simple and working answer here

const query = {} //your query here
const update = {} //your update in json here
const option = {new: true} //will return updated document

const user = await User.findOneAndUpdate(query , update, option)

Upvotes: 6

XCS
XCS

Reputation: 28177

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 ADDED
Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});

Upvotes: 775

vkarpov15
vkarpov15

Reputation: 3882

Mongoose maintainer here. You need to set the new option to true (or, equivalently, returnOriginal to false)

await User.findOneAndUpdate(filter, update, { new: true });

// Equivalent
await User.findOneAndUpdate(filter, update, { returnOriginal: false });

See Mongoose findOneAndUpdate() docs and this tutorial on updating documents in Mongoose.

Upvotes: 19

Sourabh Khurana
Sourabh Khurana

Reputation: 71

Below shows the query for mongoose's findOneAndUpdate. Here new: true is used to get the updated doc and fields is used for specific fields to get.

eg. findOneAndUpdate(conditions, update, options, callback)

await User.findOneAndUpdate({
      "_id": data.id,
    }, { $set: { name: "Amar", designation: "Software Developer" } }, {
      new: true,
      fields: {
        'name': 1,
        'designation': 1
      }
    }).exec();

Upvotes: 4

Jonathan Thurft
Jonathan Thurft

Reputation: 4173

If you want to return the altered document you need to set the option {new:true} API reference you can use Cat.findOneAndUpdate(conditions, update, options, callback) // executes

Taken by the official Mongoose API http://mongoosejs.com/docs/api.html#findoneandupdate_findOneAndUpdate you can use the following parameters

A.findOneAndUpdate(conditions, update, options, callback) // executes
A.findOneAndUpdate(conditions, update, options)  // returns Query
A.findOneAndUpdate(conditions, update, callback) // executes
A.findOneAndUpdate(conditions, update)           // returns Query
A.findOneAndUpdate()                             // returns Query

Another implementation thats is not expressed in the official API page and is what I prefer to use is the Promise base implementation that allow you to have .catch where you can deal with all your various error there.

    let cat: catInterface = {
        name: "Naomi"
    };

    Cat.findOneAndUpdate({age:17}, cat,{new: true}).then((data) =>{
        if(data === null){
            throw new Error('Cat Not Found');
        }
        res.json({ message: 'Cat updated!' })
        console.log("New cat data", data);
    }).catch( (error) => {
        /*
            Deal with all your errors here with your preferred error handle middleware / method
         */
        res.status(500).json({ message: 'Some Error!' })
        console.log(error);
    });

Upvotes: 6

Jobin Mathew
Jobin Mathew

Reputation: 483

This is the updated code for findOneAndUpdate. It works.

db.collection.findOneAndUpdate(    
  { age: 17 },      
  { $set: { name: "Naomi" } },      
  {
     returnNewDocument: true
  }    
)

Upvotes: 13

Assaf Moldavsky
Assaf Moldavsky

Reputation: 1721

For whoever stumbled across this using ES6 / ES7 style with native promises, here is a pattern you can adopt...

const user = { id: 1, name: "Fart Face 3rd"};
const userUpdate = { name: "Pizza Face" };

try {
    user = await new Promise( ( resolve, reject ) => {
        User.update( { _id: user.id }, userUpdate, { upsert: true, new: true }, ( error, obj ) => {
            if( error ) {
                console.error( JSON.stringify( error ) );
                return reject( error );
            }

            resolve( obj );
        });
    })
} catch( error ) { /* set the world on fire */ }

Upvotes: 17

user2030471
user2030471

Reputation:

By default findOneAndUpdate returns the original document. 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) {

});

Upvotes: 47

Related Questions