Categories
JavaScript Answers

How to update and return document in MongoDB?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *