How to do Pagination in Node.js using Sorting Ids ?

Implementing pagination in a Node.js application involves fetching and displaying data in chunks or pages, typically from a database. One common approach to pagination is using sorting IDs, where each record in the dataset is assigned a unique identifier (ID) that determines its position in the sorted sequence. This method allows you to efficiently retrieve data based on these IDs to implement pagination. Let’s dive into how you can achieve pagination using sorting IDs in a Node.js application.

Approach

Sorting in the NodeJS helps to sort the results in ascending or descending order. We use the sort() method in which we pass one parameter that results in ascending or descending order. Use the value -1 in the sort object to sort descending and 1 to sort the object in the ascending order.

Below are two implementations of pagination

Table of Content

  • Sorting in ascending order using IDs
  • Sorting in descending order using IDs

Steps to Setup the Project

Step 1: Create a nodeJS folder by using this command

mkdir mypp

Step 2: Navigate to the project directory

cd myapp

Step 3: Initialize the NodeJS project

npm init

Step 4: Install the necessary packages/libraries in your project using the following commands.

npm install mongoose express bcryptjs body-parser

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"express": "^4.19.2",
"mongoose": "^8.4.1"
}

MongoDB Database:

Following is the sample data stored in your database for this example.

Sorting in ascending order using IDs

JavaScript
// user.js

let mongoose = require("mongoose");

let userSchema = new mongoose.Schema({
    username:String,
    password:String
});

module.exports = mongoose.model("User",userSchema);
JavaScript
// app.js

const express = require('express'),
    Mongoose = require('mongoose'),
    Bcrypt = require('bcryptjs'),
    bodyParser = require('body-parser'),
    jsonParser = bodyParser.json(),
    User = require('./user')

const app = express();

const db = `mongodb+srv://pallavi:pallavi123@
cluster0.k0sop.mongodb.net/user?retryWrites=
true&w=majority`

Mongoose.connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
}).then(() => console.log('MongoDB Connected....'))

// Handling GET /send Request
app.get("/send", async (req, res, next) => {

    try {
        let { page, size, sort } = req.query;

        // If the page is not applied in query.
        if (!page) {

            // Make the Default value one.
            page = 1;
        }

        if (!size) {
            size = 10;
        }

        //  We have to make it integer because
        // query parameter passed is string
        const limit = parseInt(size);

        // We pass 1 for sorting data in 
        // ascending order using ids
        const user = await User.find().sort(
            { votes: 1, _id: 1 }).limit(limit)
        res.send({
            page,
            size,
            Info: user,
        });
    }
    catch (error) {
        res.sendStatus(500);
    }
});

// Handling POST /send Request
app.post('/send', jsonParser, (req, res) => {

    req.body.password = 
        Bcrypt.hashSync(req.body.password, 10);
    var newUser = new User({
        username: req.body.username,
        password: req.body.password,

    })

    newUser.save()
        .then(result => {
            console.log(result);
        });
})

// Server setup
app.listen(3000, function () {
    console.log("Express Started on Port 3000");
});

Step to Run Application: Run the application using the following command from the root directory of the project

node app.js

Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output:

Sorting in descending order using IDs

JavaScript
// user.js

let mongoose = require("mongoose");
let userSchema = new mongoose.Schema({
    username:String,
    password:String
});

module.exports = mongoose.model("User", userSchema);
JavaScript
// app.js

let express = require('express'),
    Mongoose = require('mongoose'),
    Bcrypt = require('bcryptjs'),
    bodyParser = require('body-parser'),
    jsonParser = bodyParser.json(),
    User = require('./user')

const app = express();

const db = `mongodb+srv://pallavi:pallavi123
@cluster0.k0sop.mongodb.net/user?
retryWrites=true&w=majority`

Mongoose.connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
}).then(() => console.log('MongoDB Connected....'))

// Handling GET /send Request
app.get("/send", async (req, res, next) => {
    try {
        let { page, size, sort } = req.query;

        // If the page is not applied in query
        if (!page) {

            // Make the Default value one
            page = 1;
        }

        if (!size) {
            size = 10;
        }

        //  We have to make it integer because
        // the query parameter passed is string
        const limit = parseInt(size);

        // We pass 1 for sorting data in 
        // descending order using ids
        const user = await User.find().sort(
            { votes: 1, _id: -1 }).limit(limit)

        res.send({
            page,
            size,
            Info: user,
        });
    }
    catch (error) {
        res.sendStatus(500);
    }
});

// Handling POST /send Request
app.post('/send', jsonParser, (req, res) => {

    req.body.password = 
        Bcrypt.hashSync(req.body.password, 10);
        
    let newUser = new User({
        username: req.body.username,
        password: req.body.password,

    })

    newUser.
        save()
        .then(result => {
            console.log(result);

        });
})

// Server setup
app.listen(3000, function () {
    console.log("Express Started on Port 3000");
});

Step to Run Application: Run the application using the following command from the root directory of the project

node app.js

Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output: