How to use mongoose to find by id and update with an example

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

Introduction

In this quick tutorial we will demo how to use mongoose to find by id and update with an example.

The update operation is one of the CRUD operations that is used to update data in a database. Out of all the CRUD operations, the update operation should be performed very carefully. You see, if we need to update a single record out of hundreds of records, and we end up updating a wrong record, it can cause trouble. So every time, it should be done very carefully. MongoDB provides a few methods for updating data. One of these method is findByIdAndUpdate() method.

The findByIdAndUpdate() method matches a single document and then updates it. This method needs a string value, which is the value of the _id field. As the _id field is unique throughout the collection, there is no margin of error. In this article, we will discuss how to use the findByIdAndUpdate() in mongoose with the help of an example.

We find it helpful to use a small data set for demonstration so for this example we will use the following kennels collection. Each document represents a dog and contains fields for a “name” and a “breed”.

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.

NOTE We have used the express package to help create our endpoints. The express package simplifies the process of creating routes and is very popular package in NodeJs for creating APIs. The express package can be installed through npm and required into your script. npm install express is the npm command to install the package.

1
2
3
4
5
6
7
8
9
10
11
12
13
router.route('/update').post(function(req,res){

    kennels.findByIdAndUpdate({"5db6b26730f133b65dbbe459"},{"breed": "Great Dane"}, function(err, result){

        if(err){
            res.send(err)
        }
        else{
            res.send(result)
        }

    })
})

The third parameter to findByIdAndUpdate 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. This is very important to note because it is counter-intuitive and a common mistake made when using this function.

The findByIdAndUpdate() method 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.

Conclusion

We have covered how to use the findByIdAndUpdate() method in mongoose, what it does, what it returns, what parameters it takes, as well as a basic demo of how to use it. We hope the info provided here was helpful.

NOTE We want to re-emphasize that the findByIdAndUpdate method DOES NOT return the updated document. It returns the document that WILL BE updated. This is a common mistake and we hope this saves you some debug time!

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.