Sometimes, we want to update and return document in MongoDB.
In this article, we’ll look at how to update and return document in MongoDB.
How to update and return document in MongoDB?
To update and return document in MongoDB, we can call findAndUpdare
with the returnOriginal
option set to false
.
For instance, we write
collection.findOneAndUpdate({
code
}, {
$set: updatedFields
}, {
returnOriginal: false
},
(err, documents) => {
//...
db.close();
}
);
to call findOneAndUpdate
to update the entries with code
set to code
with the updatedFields
object values.
We set returnOriginal
to false
so that documents
in the callback would return the updated versions of the updated documents.
Finally, we call db.close
to close the database connection.
Conclusion
To update and return document in MongoDB, we can call findAndUpdare
with the returnOriginal
option set to false
.