Categories
JavaScript Answers

How to fix Mongoose findOneAndUpdate doesn’t return updated document?

Spread the love

Sometimes, we want to fix Mongoose findOneAndUpdate doesn’t return updated document.

In this article, we’ll look at how to fix Mongoose findOneAndUpdate doesn’t return updated document.

How to fix Mongoose findOneAndUpdate doesn’t return updated document?

To fix Mongoose findOneAndUpdate doesn’t return updated document, we call findOneAndUoate with the new option set to true.

for instance, we write

Cat.findOneAndUpdate({
  age: 100
}, {
  $set: {
    name: "jane"
  }
}, {
  new: true
}, (err, doc) => {
  if (err) {
    console.log("Something wrong when updating data!");
  }
  console.log(doc);
});

to call findOneAndUpdate with an object that sets new to true to return the new document as the value of doc.

We set name to 'jane' where the Cat entry has age value 100.

Conclusion

To fix Mongoose findOneAndUpdate doesn’t return updated document, we call findOneAndUoate with the new option set to true.

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 *