Get the updated document in MongoDB

2020-07-13 07:48发布

问题:

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?

回答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.



回答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