How to Add Pagination in REST API using Node JS and Mongoose

Hey there fellow developers! Today, I'm excited to share a comprehensive guide on adding pagination to your REST API using Node.js and Mongoose. Pagination is a crucial feature for any API dealing with large datasets, as it allows you to efficiently manage and present data to your users in manageable chunks.

In this article, we'll see how to create a paginated API with MongoDB and Node JS.

So, let's see how to add pagination in REST API using Node JS and Mongoose, Mongoose pagination, Node express Mongoose pagination, server side pagination in Node JS MongoDB, pagination in Mongoose Node JS.

Step 1: Setting Up Your Node.js Project

First things first, make sure you have Node.js installed on your system. You can download and install it from the official Node.js website if you haven't already.

Once Node.js is set up, create a new directory for your project and navigate into it using your terminal or command prompt.

Now, let's initialize a new Node.js project by running the following command:

npm init -y

This command will create a package.json file with default values.

 

Step 2: Installing Mongoose

Mongoose is an elegant MongoDB object modeling tool designed to work in an asynchronous environment. To install Mongoose, run the following command in your terminal:

npm install express mongoose

 

Step 3: Connecting to MongoDB

Before we can start pagination, we need to connect our Node.js application to MongoDB using Mongoose. Create a new file called db.js in your project directory and add the following code:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydatabase')
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Failed to connect to MongoDB', err));

Make sure to replace 'mongodb://localhost:27017/mydatabase' with the connection URL of your MongoDB database.

 

Step 4: Creating a Mongoose Schema

Now, let's define a Mongoose schema for the documents in our MongoDB collection. Create a new file called products.js in your project directory and add the following code:

models/products.js

const mongoose = require("mongoose");

const productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, "Name must be required"]
    },
    price: {
        type: Number,
        required: [true, "Price must be required"]
    },
    featured: {
        type: Boolean,
        default: false
    },
    rating: {
        type: Number,
        default: 4.5
    },
    createdAt: {
        type: Date,
        default: Date.now()
    },
    company: {
        type: String,
        enum: {
            values: ['Apple', 'Samsung', 'Dell', 'HP'],
        }
    }
});

module.exports = mongoose.model("Product", productSchema);

 

Step 5: Implementing Pagination

Now, let's implement pagination in our API. We'll add a route to fetch paginated data from our MongoDB database.

const Product = require("../models/products");

const getAllProducts = async (req, res) => {    
    const queryObject = {};

    let apiData = Product.find(queryObject);

    let page = Number(req.query.page) || 1;
    let limit = Number(req.query.limit) || 10;

    let skip = (page - 1) * limit;

    apiData = apiData.skip(skip).limit(limit);

    const products = await apiData;
    res.status(200).json({ products, totalRecords: products.length })
};

module.exports = getAllProducts;

Output:

http://localhost:5000/api/products?page=1&limit=2

API Response 

{
    "products": [
        {
            "_id": "65dc301f352a919d18074cb7",
            "name": "Iphone14",
            "price": 170,
            "featured": true,
            "rating": 4.5,
            "createdAt": "2024-02-26T06:30:54.492Z",
            "company": "Apple",
            "__v": 0
        },
        {
            "_id": "65dc301f352a919d18074cb8",
            "name": "N4030",
            "price": 200,
            "featured": true,
            "rating": 4.5,
            "createdAt": "2024-02-26T06:30:54.492Z",
            "company": "Dell",
            "__v": 0
        }
    ],
        "totalRecords": 2
}

 

Step 6: Conclusion

Congratulations! You've successfully implemented pagination in your REST API using Node.js and Mongoose.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS