How to Use the Mongoose findByIdAndUpdate Method

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

Introduction

Updating data from a database can become hectic when there is way too much data. Mongoose provides a lot of methods to update data from MongoDB. Each of these methods is useful in their own way. One of these methods is the findByIdAndUpdate() method. The findByIdAndUpdate() method is specifically used to find a document by providing the value of the auto-generated _id field and then update the content of the document. In this article, we will learn how to use the Mongoose findByIdAndUpdate() method.

We will use the kennels collection 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" : "Labrador" }
{ "_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.

findByIdAndUpdate()

The findByIdAndUpdate() method has two mandatory parameters – the value of the _id field of the document and the update.

Let’s change the value of the breed field where the name is “Spike”. The value of _id field here is “5db6b26730f133b65dbbe459”. Let’s change the breed to do “Great Dane”.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
router.route("/update").post(function(req, res) {
  kennels.findByIdAndUpdate(
    { _id: "5db6b26730f133b65dbbe459" },
    { breed: "Great Dane" },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

The third parameter is a callback function, that in turn has two parameters – an error (if any occurs) and the result. Let’s execute the endpoint using the postman tool and check what is the output.

Image from Gyazo

It returns an object but the value of the breed field is not updated. Let’s check through the mongo shell.

Image from Gyazo

We changed the value of the breed field of the third document. And we can see, here the value is “Great Dane”. This means, the findByIdAndUpdate() method worked perfectly. But why does the value in the returned object was unchanged? This is because the findByIdAndUpdate() method returns that matched the condition before the update operation.

Upsert

So what will happen if the value of the _id field specified does not match any document? Absolutely nothing!

Suppose, we want to add a new document if the value of the _id field does not match. We can use the upsert option. The upsert option will add a new document and this new document will contain the content of the update that was passed to the findByIdAndUpdate() method.

Observe the following route handler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
router.route("/update").post(function(req, res) {
  kennels.findByIdAndUpdate(
    { _id: "5db6b11730f133b65dbbe459" },
    { breed: "Great Dane" },
    { upsert: true },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

The findByIdAndUpdate() method does not return anything in this case. Let’s check through the mongo shell.

Image from Gyazo

We can see there is a new document with the same content as the update we passed to the findByIdAndUpdate() method.

Conclusion

As mentioned earlier, there are many methods for updating data in MongoDB. The findByIdAndUpdate() is one of these methods and it is very useful when you have to update a specific document. The value of the _id field is always unique in a collection and there is no margin of error when we use the findByIdAndUpdate() method.

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.