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?
To get last inserted document, use sort() along with limit(1).
In MongoDB, updateOne() method updates a first matched document within the collection based on the given query. When you update your document the value of the _id field remains unchanged. This method updates one document at a time and can also add new fields in the given document.
The update() method updates the values in the existing document in the collections of MongoDB. When you update your document the value of the _id field remains unchanged. By default, the db. collection. update() method updates a single document.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With