Mongoose: findOneAndUpdate doesn't return updated document

findoneandupdate mongoose
mongoose findoneandupdate callback
mongoose findoneandupdate deprecated
mongoose findoneandupdate promise
mongoose updateone
mongoose updateone example
mongoose findoneandupdate upsert
mongodb findoneandupdate nodejs example

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.

findOneAndUpdate(), Mongoose's findOneAndUpdate() is slightly different from the MongoDB Node.js That means you can assume the document doesn't change between when  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.

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

Mongoose: findOneAndUpdate doesn't return updated , Anyone who is using the Node.js driver instead of Mongoose, you'll want to use {​returnOriginal:false}instead of {new:true}. I have separated my Mongoose code in model.js file, while Express code for handling http requests is in app.js. I'm just practising creating APIs and testing them on Postman, for an imaginary wiki

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

How to Use the Mongoose findOneAndUpdate Method, Now, we did not provide any query, so the findOneAndUpdate() method does not know which to document update. What do you think will happen  You're correct. media is an array/list. I've confused myself by pasting in a snippet (which I stripped), the document example above was not correct. My apologies and I thank you for being persistent.

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) {

});

db.collection.findOneAndUpdate(), findOneAndUpdate (filter, update, options)¶. mongo Shell Method. This page documents the mongo shell method, and does not refer to the MongoDB Node.js​  This seems like a fairly common use case, but I've looked through the Mongoose docs and I can't find anything. Mongoose Collection methods like findOneAndUpdate() and update() with upsert: true are about modifying documents - I don't wish to modify the document if it exists, just get a reference to it.

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 */ }

findOneAndUpdate is not working · Issue #2248 · Automattic , findOneAndUpdate is not working #2248 node-mongodb-native: 1.4.8 Hi @​abernardobr, what does your mongoose schema look like? Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

MongoDB, As MongoDB Github collection documented with respect to Node.js MongoDB Driver API here Find a document and update it in one atomic  This page documents the mongo shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead. Updates a single document based on the filter and sort criteria. The findOneAndUpdate () method has the following form:

How to return the updated document on Mongoose, Using any find & update function like findByIdAndUpdate() , findAndUpdate() or findOneAndUpdate() just add the third param with new: true . Mongoose: findOneAndUpdate doesn't return updated document - Wikitechy. HOT QUESTIONS. What is difference between class and interface in C#; Mongoose.js: Find user by username LIKE value

MongoDB and Mongoose, It seems there is a bug in the testing. It updates and returns in updated record in the console. However, it does not pass teh test. can anyone tell  Above, we opted for the use of the Mongoose shortcut method findByIdAndUpdate (there's also a findOneAndUpdate).Check out the documentation here: findOneAndUpdate(), findByIdAndUpdate(). Another option would be to use a findOne or findById, make the changes to the properties manually, then use.save to save the change.

Comments
  • This appears to be broken for me, it still returns the old document with new: true.
  • @PDN What version of mongoose/mongo do you have? That might be messing with how it works.
  • makes sense to me since you already have access to the new document
  • it worked for me, I'm using moogose version 4.6.3, thanks
  • for those reading here, who might still find that "new": true doesn't work, check that the field you update and expect to see in the found object is added to the Schema
  • Thank you! This works for me mongodb node version 2.2.27
  • This is kind of an idiot API. Why not use the same signatures for Mongoose as the native API? Why not return the updated doc by default? Mongoose is one of the more irritating libs I use everyday.
  • you're real mvp there for me :D
  • Laravel: 'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER
  • why is _id null?
  • Mongoose will return a promise if you don't provide a callback function. There is no need to create your own promise!
  • @joeytwiddle Mongoose will not return a Promise if you don't provide a callback. Instead it returns a Query object that provides only a small subset of the Promise API. This is according to the Mongoose documentation.
  • I have mistaken to write returnNewDocument instead of just new. thanks for help!