How to Use the Mongoose findOneAndUpdate Method

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Updating data is a critical task. While performing the update operations, we should keep in mind, that a little mistake can cause a big problem. Mongoose provides many effective methods for updating data. These methods are designed for a single purpose (i.e. updating) but they work differently. One of these methods is findOneAndUpdate(). In this article, we will discuss the Mongoose findOneAndUpdate() method and how to use it for updating data in MongoDB.

We will use the kennels collections for demonstration.

1
2
3
4
5
{ "_id" : ObjectId("5db6b24830f133b65dbbe457"), "name" : "Rocky", "age" : 3, "breed" : "Labrador" }
{ "_id" : ObjectId("5db6b25b30f133b65dbbe458"), "name" : "Max", "age" : 2, "breed" : "German Shephard" }
{ "_id" : ObjectId("5db6b26730f133b65dbbe459"), "name" : "Spike", "age" : 3, "breed" : "Great Dane" }
{ "_id" : ObjectId("5db6b27530f133b65dbbe45a"), "name" : "Tyke", "age" : 4, "breed" : "Pitbull" }
{ "_id" : ObjectId("5db6b28d30f133b65dbbe45b"), "name" : "Romeo", "age" : 2, "breed" : "Labrador" }

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

findOneAndUpdate()

As the name suggests, the findOneAndUpdate() method finds a single document in a collection and then, updates it.

The following route handler will be invoked when the endpoint ‘/update’ will be executed.

1
2
3
4
5
6
7
8
9
router.route("/update").post(function(req, res) {
  kennels.findOneAndUpdate({}, { age: 5 }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

The findOneAndUpdate() method has three parameters – an object that may or may not hold a query, the update, and a callback function. The callback function, in turn, has two parameters – an error (if any occurs) and the result.

Above, we passed an empty object as the first parameter, and the second object is the update. It will update the age field to 5. Now, we did not provide any query, so the findOneAndUpdate() method does not know which to document update. What do you think will happen? Let’s check this by using the postman tool.

Image from Gyazo

It returns the first object of the collection. Yes, when there is no query specified, the findOneAndUpdate() method updates the very first document of the collection. But the age is not updated. It is still the same. Let’s cross-check it using the mongo shell.

Image from Gyazo

We can see, the age field of the first document is changed to 5. This is exactly what we wanted. So, the findOneAndUpdate() method only returns the document that is matched before updating it.

1
2
3
4
5
6
7
8
9
10
11
12
router.route("/update").post(function(req, res) {
  kennels.findOneAndUpdate({ breed: "Labrador" }, { name: "Mini" }, function(
    err,
    result
  ) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

The above findOneAndUpdate() will find the document where the breed is “Labrador” and update the name field to “Mini”. But check the kennel’s collection. There are two documents where the value of the breed field is “Labrador”. Let’s execute the route and see what happens.

Image from Gyazo

As discussed earlier, the findOneAndUpdate() method returns the matched document before updating it. So we can see, it matched the first document where the breed is “Labrador”. This is how the findOneAndUpdate() method works. It does not matter how many documents can match the query, the findOneAndUpdate() will only update the first document which is matched. All other documents will be ignored. Let’s check using the mongo shell.

Image from Gyazo

Yes! the name field of the first document where the value of the breed field is “Labrador” is updated.

Conclusion

Thank you for reading this article on how to use the Mongoose findOneAndUpdate() method. We hope you can apply what you’ve learned to your specific application. If you have any questions please reach out to us.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.