Mongoose findById() Function: Selecting MongoDB Document by ID

As a MERN fan, we all have a favourite database, MongoDB. While working with it we usually use the find() method to select or query multiple documents, on the other hand, we use findOne() to get one. 

We can also use this findOne() with an ID passed as a query to select that specific ID-contained document. But there is a better and more straightforward way to do so, introducing findById() from Mongoose.

Well, why Mongoose? Why not MongoDB? MongoDB has no such function that lets us quickly select a document based on the document ID. This function is not a native MongoDB function but is only provided by Mongoose.

In this tutorial, we will not only look at its basics but also demonstrate it with a complete example.

Mongoose findById() Function

Mongoose is an ODM (Object Document Mapper). It is also called an object modelling tool. It is built on top of the MongoDB driver making it easier to interact with the MongoDB database, especially while using Node.js. The functions provided by Mongoose are beginner-friendly, easy to use, and require fewer lines of code than MongoDB native functions. One such function is findById() to match a document based on ID, let’s see its syntax.

Syntax of findById() Function

collection.findById(id, callback);

Parameters:

  • collection: A Mongoose model that represents a MongoDB collection,
  • id: The ID of a document you want to get,
  • callback: A callback function that is executed when a document is found or an error occurs.

Note:

It also takes some optional parameters, which isn’t that big of a use case. Check out the official docs if you want to learn about them.

Return:

The function itself returns not a document but a Mongoose Query object that you can use inside the callback to perform further operations or print it. If documents are not found, the callback will receive null.

Complete Guide to Using findById() with Node.js and MongoDB

Well now that we have learned all the basics, syntax and parameters, let’s see how to implement it in Node.js to filter documents.

Below is a step-by-step guide to using the findById() in a Node.js application with the help of Mongoose ODM:

Step 1: Create a Node.js project directory and move into it.

mkdir newNodeProject
cd newNodeProject

Step 2: Initialise the Node.js project inside the directory using npm.

npm init -y

This command will now create a “package.json” file in the directory, here you will be able to change the entry point file name by changing the “main” key. However, let’s now stick to the default.

Step 3: Create the entry point JavaScript file.

touch index.js

Step 4: Next, install all the required packages for this application.

npm i express mongoose

Step 5: Import all the packages we installed. We will use the require() method to achieve this. You can simply copy the code below in the index.js file.

const express = require('express');
const app = express();
const mongoose = require('mongoose');

Step 6: Next, connect the application to the MongoDB local database server using Mongoose.

mongoose.connect('mongodb://localhost:27017/someRandomDB', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log(`CONNECTED TO MONGO!`);
    })
    .catch((err) => {
        console.log(`OH NO! MONGO CONNECTION ERROR!`);
        console.log(err);
    })

Step 7: Now at the very end of the index.js file, specify the port for the app to listen on.

app.listen(3000, () => {
    console.log('Connected to PORT 3000...');
})

Step 8: In your project directory, create a folder named “models”.

mkdir models

We usually do this when to conform to the MVC (Models, Views, & Controllers) format when using Express. However, you can simply choose to add the contents of the file in the index.js file. But for standards, we will choose to create a model directory.

Step 9: If you choose to create a “models” directory, create a new file inside that directory named first_model.js or anything you like.

touch models/first_model.js

Step 10: Import Mongoose and create a schema and model in this file. Let’s say we are managing a mini-shoe store database. This is what our products’ schema would look like.

const mongoose = require('mongoose');
const shoeSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true,
        min: 0
    },
    sizeUK: {
        type: Number,
        required: true,
        min: 5
    },
    onSale: {
        type: Boolean,
        default: false
    }
})
 
const Shoe = mongoose.model('Shoe', productSchema);

Step 11: To work with the findbyId(), we have created and saved a few documents in the “shoes” collection.

{ "_id" : 1000, "name" : "Nike Air Force 1", "price" : 4,999, "sizeUK" : 6, "onSale" : false }
{ "_id" : 1001, "name" : "X Speedflow.4 Flexible Ground Boots", "price" : 5,999, "sizeUK" : 7, "onSale" : true }
{ "_id" : 1002, "name" : "Men's Reebok Running Ztaur Run Shoes", "price" : 9,999, "sizeUK" : 9, "onSale" : true }
{ "_id" : 1003, "name" : "Puma RS - Z Art of Sport Unisex Sneakers", "price" : 8,999, "sizeUK" : 8, "onSale" : true }

Step 12: Let us now use the findbyId() on these documents to find a document containing a specific ID field.

const id = 1002;

Shoe.findById(id, function (err, shoe) {
    if (err) throw error;
    console.log(`Item(s) found: ${shoe.name}`);
});

Inside the callback, check for an error and throw it if it is present, if not then print the selected document in the console.

Step 13: Finally, you can run the app to see if it works.

node models/first_model.js

Output:

Item(s) found: Men's Reebok Running Ztaur Run Shoes

This way we have successfully used the findById() function to find a document by its ID.

Read More: Listing All Collections, Databases, and Users in the MongoDB Shell

Conclusion

This is the end of this tutorial and if you are still here appreciate yourself, very few people make it this far. We hope you have got enough information on find by ID. We also gave you some knowledge of how to set up a basic Node application, connect to the MongoDB database, use Mongoose, etc. The purpose of building this big application is not just to explain to you how to use the findById(), but also to give you its complete case use. 

Aneesha S
Aneesha S
Articles: 171