Basic Guide to MongoDB findById Function

In MongoDB, the findbyId() function is of great use when developers want to integrate features that allow users to edit things on the basis of IDs. This function facilitates the development of applications that involve heavy CRUD operations. Examples of use cases of such applications include dashboard integrations, forums, eCommerce platforms, reviews, listing platforms, etc.

We already have covered the find() and findOne() methods, in this tutorial we will provide a comprehensive guide to using the method findById() of MongoDB in Nodejs. We will demonstrate with an example using Nodejs with the help of Mongoose.

Guide to Using findById() Function with Nodejs & Mongoose

Let us start with our simple step-by-step guide to using the findById() function in a Nodejs application with the help of the Mongoose ODM for MongoDB.

Follow the steps below to get started:

  • Create a Nodejs project directory and move into it:
mkdir newNodeProject
cd newNodeProject
  • Create your Nodejs project inside the directory like this:
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, I will stick to the default.

  • Create the entry point JavaScript file:
touch index.js
  • Next, let us install all the required packages for this application:
npm i express mongoose
  • We shall now 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');
  • Next, we shall connect our application to the MongoDB local database server using Mongoose like this:
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!`);
  • Now, at the far end of the index.js file, I am going to set up my port for my app to listen:
app.listen(3000, () => {
    console.log('Connected to PORT 3000...');
  • Next, 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. However, I will simply choose to create a models directory.

  • Now, if you choose to create a models directory, then create a new file named inside the directory named first_model.js, or anything you’d like.
touch models/first_model.js
  • Let us import mongoose and create our first schema and model in this file. Let’s say I am 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);
  • To work with the findbyId() function, I have created and saved a few documents in my 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 }
  • Let us now use the findbyId() function on these documents for finding a document containing a given id field:
const id = 1002;

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

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

  • Finally, you can run your app to see if it works:
node models/first_model.js

This is what our console prints:

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 [Easy 2021 Guide]


Finding, updating, deleting, or removing data from the dummy database, is part and parcel of software or web development. Moreover, these are operations that are crucial for almost any application. findById() function gives the power to find the MongoDB document on the basis of its id and perform these operations on them

In this tutorial, we have guided you on using the findById() function in MongoDB. Hope this will help.

Noteworthy References

Aneesha S
Aneesha S
Articles: 173