NodeJS MongoDB Find by Id

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

Introduction

NodeJS can be used with various databases such as MySQL and MongoDB. In this tutorial we’ll show you both how to find a document by id using plain MongoDB and also using the library Mongoose. Mongoose is one Object Document Mapper that allows us to define objects with a strongly-typed schema that could be mapped to a MongoDB document. Mongoose provides several helper functions for CRUD operations. One of these functions is findByID. In this article, we will discuss the findByID function.

findByID using Mongoose

As the name suggests, the findByID method is used to find documents by specifying a certain id. By id, it means, the automatically created _id field whenever a document is created. The _id field is a unique value. So it is possible to use the value of _id to retrieve the document.

We have details collection. There are three documents in the details collection.

1
2
3
{ "_id" : ObjectId("5d71522dc452f78e335d2d8b"), "name" : "John", "age" : 21, "location" : "New York" }
{ "_id" : ObjectId("5d715243c452f78e335d2d8c"), "name" : "Sam", "age" : 23, "location" : "Chicago" }
{ "_id" : ObjectId("5d71524ec452f78e335d2d8d"), "name" : "Lisa", "age" : 25, "location" : "Texas" }

In mongoose if we need to use the findByID function, we need to pass the id of a particular document. Let’s see how can we use the findByID function to fetch the first document of the details collection.

1
2
3
4
5
6
7
Details.findById(ObjectId("5d71522dc452f78e335d2d8b"))
  .then(doc => {
    console.log(doc);
  })
  .catch(err => {
    console.log(err);
  });

Let’s look at the piece of code above step by step.

  1. First of all, we need to define the schema for MongoDB. Here we are using the details schema. Let’s see how can we define for the documents in the detail collection.
1
2
3
4
5
6
7
8
9
const mongoose = require("mongoose");

const detailsSchema = mongoose.Schema({
  name: String,
  age: Number,
  location: String
});

module.exports = mongoose.model("Details", detailsSchema);

We create a schema named detailsSchema. It is exported and can be accessed as “Details” by importing in the file we want. To use the findById method we used this Details schema.

1
Details.findById(ObjectId("5d71522dc452f78e335d2d8b"));
  1. Observe the parameter of the findById function. It is the exact value of the _id field.
1
ObjectId("5d71522dc452f78e335d2d8b");

If we only pass the actual id, i.e. 5d71522dc452f78e335d2d8b, it will not work.

  1. The function returns a promise, and we have to handle it accordingly.
1
2
3
4
5
.then((doc)=>{
    console.log(doc);
 }).catch((err)=>{
    console.log(err);
 });

If the operation is successful, the argument received – doc, will contain the returned document otherwise, the error will be thrown.

Without Mongoose

Remember you don’t have to use Mongoose. You can always use tried and true MongoDB and to find a document by id you could use the find or findOne methods and provide the id as the argument which would look something like this:

1
collection.find({ _id: ObjectId("5d71522dc452f78e335d2d8b") });

or

1
collection.findOne({ _id: ObjectId("5d71522dc452f78e335d2d8b") });

Conclusion

The findByID function is useful when data needs to be retrieved using the _id field. It actually triggers the findOne function. It returns a promise and needs to be handled accordingly. We have demonstrated how to do this and hope you can apply what you’ve learned to your code.

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.