Get the updated document in MongoDB

I need to get the _id (the Mongo ObjectID) of updated document. For this I want to get the updated document. How can I get it?

I tried this:

...
collection.update(oldData, newData, function(err, doc) {
    console.log(docs); // This prints "1" in console. So, it's not a document.
    if (err) { return callback(err); }
    callback(null, doc);
});
...

Can I get it without finding a document by newData/oldData?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Instead of using .update(), I think you want to use .findAndModify().

An update can update multiple documents, and the second argument of its callback is the number of updated documents (in your case, 1).

With findAndModify, you can update exactly one document (read the documentation on exactly how it differs from update), and the updated document will be passed to the callback function.

Solution 2

In nodejs API solution is to set: {returnOriginal: false}.

collection.findOneAndUpdate(
        whereObj,
        updateObj,
        {returnOriginal: false});

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply