Basic Guide to MongoDB findById Function

MongoDB FindById Featured Image

In this tutorial, I am going to introduce the MongoDB findById function.

The MongoDB findbyId function is of great use when developers want to integrate features that allow users to edit things. These functions facilitate the development of applications that involve heavy CRUD operations. Examples of use cases of such applications include dashboard integrations, forums, eCommerce platforms, reviews and listing platforms, and the like.

With a robust JavaScript framework technology like Nodejs, database management systems like MongoDB fit very well. Moreover, a perfect ODM is what such a smooth and flexible DBMS requires. This is where Mongoose is into the picture.

With the integration of all these technologies, I will guide you on using the MongoDB findById function. Finding, updating, deleting, or removing data from the dummy database, are part and parcel of software or web development. Moreover, these are operations that are crucial for almost any application.

In this tutorial, I will guide you on using the MongoDB findById function. I will demonstrate with an example using Nodejs with the help of Mongoose.

So, let us get started without wasting much time!

Guide to Using MongoDB findById Function with Nodejs & Mongoose

Let us start with our simple step-by-step guide to using every MongoDB 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 module 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!`);
        console.log(err);
    })
  • 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 how 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 MongoDB findbyId, 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 MongoDB findById function on these documents:
const id = 1002;

Shoe.findById(id, function (err, shoe) {
    if (err) throw error;
    console.log(`Item(s) found: ${shoe.name}`);
});
  • 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 MongoDB findById function. The findById comes with other more variants of functions. Let me know in the comments if you want me to create tutorials on them.

Read More: Listing All Collections, Databases, and Users in the MongoDB Shell [Easy 2021 Guide]

Conclusion

Finding, updating, deleting, or removing data from the dummy database, are part and parcel of software or web development. Moreover, these are operations that are crucial for almost any application.

With a robust JavaScript framework technology like Nodejs, database management systems like MongoDB fit very well. Moreover, a perfect ODM is what such a smooth and flexible DBMS requires. This is where Mongoose is into the picture.

With the integration of all these technologies, I will guide you on using the MongoDB findById function.

Noteworthy References

Mongoose Docs