How to use NodeJs mongoose to find the object ID

Introduction

Read operation is one of the CRUD operations that can be performed on a database. Mongoose provides a few methods to read the data from a database. Each method has its own specialty. We can use these methods according to our requirements. One of these methods is the findById() method. As the name suggests, the findById() method is used to find a document by its id. In this article, we will discuss more about the findById() method and how to use it in mongoose.

How to use findById()

Whenever a document is inserted into a MongoDB collection, the _id field is automatically generated. This _id field acts as a primary key and its value is unique for each document in the collection. We can say, the _id field acts as the primary key. So this field can be useful in many ways. As its value is unique in each document, we can easily use it for getting a particular document. That is why mongoose provides the findById() method. All we need to do is specify the value of the _id field, and the findById() method will retrieve the document. Let’s discuss how to use it.

To demonstrate how to use the findById() method we find it useful to use a sample data set so we have the following smartphones collection:

{ "_id" : ObjectId("5e12d83b86d564bd4487658a"), "name" : "Apple Iphone 11", "price" : 1000, "inStock" : true }
{ "_id" : ObjectId("5e12d84c86d564bd4487658b"), "name" : "Samsung S10", "price" : 800, "inStock" : true }
{ "_id" : ObjectId("5e12d86186d564bd4487658c"), "name" : "Apple Iphone 11 pro", "price" : 1200, "inStock" : false }
{ "_id" : ObjectId("5e12d8bf86d564bd4487658d"), "name" : "Huawei P30 pro", "price" : 900, "inStock" : false }
{ "_id" : ObjectId("5e12d91486d564bd4487658e"), "name" : "Apple Iphone 11 pro max", "price" : 1400, "inStock" : true }

Our intent is to fetch the document where the value of the _id field is “5e12d86186d564bd4487658c”.

The following route handler will be invoked when the endpoint ‘/find’ is executed. We created this route handler in NodeJs using the express package that is a popular choice for creating API routes in NodeJS. It’s easy to install and use with npm. npm install express is all you should need to do and then put the require statement at the top of your js file. If you need more assistance setting up express there are extensive tutorials online.

router.route("/find").get(function(req, res) {});

Now that we’ve setup the route that will handle our API request we will add the code to execute when that endpoint is hit. This is where we will put our findById() method. Below is our full route handler:

router.route("/find").get(function(req, res) {
  smartphones.findById("5e12d86186d564bd4487658c", function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Let’s focus in on just the use of the findById() to keep this very simple. To use the findById() method we just have to pass ID value as the first parameter of the findById() method. Let’s execute this route using the postman tool and see what happens. You can download the postman tool from www.getpostman.com.

Image from Gyazo

Yes! It retrieves the document where the value of the _id field is “5e12d86186d564bd4487658c”.

Conclusion

The findById() is a fundamental method to know because finding a document by ID is one of the most common methods used when working with databases. As you saw it’s very simple to use, all you need to do is pass in the ID value to the function and it will return document matching the ID. As the second argument it takes in a callback that either returns the result of the query or an error if one occurred. We handled both cases in our route. In most applications with NodeJs, MongoDB, and mongoose you will commonly see many routes setup similar to this basic one we demonstrated.

We hope this tutorial was helpful to you. Thanks for joining us for another ObjectRocket tutorial!

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.