Pagination - Node JS, Mongo DB, Express

Pagination – Node JS, Mongo DB, Express

In this tutorial, we are going to create a simple pagination program in Node JS and Mongo DB. For the sake of simplicity, we will be using the Express framework. If you prefer a video tutorial over a textual tutorial, then you can follow the video tutorial below:

Video Tutorial

Pagination – Node JS, Mongo DB, Express

Mongo DB Data

First, we are going to fill the data in Mongo DB. You can apply this tutorial to your own collections and documents. Or you can import the following (at the end) JSON file in your database using Mongo DB compass. You need to create a database named “pagination_nodejs_mongodb” before importing the file.

Setup the Project

Create an empty new folder and enter it with the following commands from Terminal:

mkdir pagination-nodejs-mongodb
cd pagination-nodejs-mongodb

Once in the folder, you can install the required modules by running the following commands:

npm install express http mongodb ejs
npm install -g nodemon

The express framework is used to create web applications and APIs, and we will be creating an API to fetch the data for pagination. HTTP module will be used to start the server at a specific port. Mongo DB module will be used to connect and interact with the Mongo DB database. And finally, EJS will be used to render HTML files.

Create a file named “server.js” and write the following code in it:

// initialize express framework
var express = require("express");
var app = express();

// create http server
var http = require("http").createServer(app);

// start the server
http.listen(3000, function () {
    console.log("Server started at port 3000");
});

Run the following command to start the server.

nodemon server.js

This will start the server at port 3000. If you open your terminal, you will see the above message.

Pagination

Now you need to include the Mongo DB module, write the following lines before line 8.

// include mongo DB module
var mongodb = require("mongodb");
var mongoClient = mongodb.MongoClient;
var ObjectId = mongodb.ObjectId;

Then you can connect with Mongo DB server. You need to write the following lines inside http.listen function callback (2nd parameter):

// connect with mongo DB server and database
mongoClient.connect("mongodb://localhost:27017", {
    useUnifiedTopology: true
}, function (error, client) {
    var database = client.db("pagination_nodejs_mongodb");
    console.log("Database connected.");
});

If you check your terminal now, you will see a second message that your database has been connected. Now we need to create a GET route which when accessed will display 2 users per page from the users collection data. So paste the following lines after the database is connected:

// create a GET HTTP route
app.get("/", async function (request, result) {

    // number of records you want to show per page
    var perPage = 2;

    // total number of records from database
    var total = await database.collection("users").count();

    // Calculating number of pagination links required
    var pages = Math.ceil(total / perPage);

    // get current page number
    var pageNumber = (request.query.page == null) ? 1 : request.query.page;

    // get records to skip
    var startFrom = (pageNumber - 1) * perPage;

    // get data from mongo DB using pagination
    var users = await database.collection("users").find({})
        .sort({ "id": -1 })
        .skip(startFrom)
        .limit(perPage)
        .toArray();

    // render an HTML page with number of pages, and users data
    result.render("index", {
        "pages": pages,
        "users": users
    });
});

Comments has been added with each line for explanation. To display the HTML file, we need to tell the Express framework that we will be using EJS engine. Write the following line before the http.listen function:

// set the view engine as EJS for displaying HTML files
app.set("view engine", "ejs");

Create a folder named “views” at the root of your project. Inside the views folder, create a file named “index.ejs”. Following will be the content of “index.ejs” file:

<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
    </tr>

    <tbody>
        <% for (var a = 0; a < users.length; a++) { %>
        <tr>
            <td><%= users[a].name  %></td>
            <td><%= users[a].age  %></td>
        </tr>
        <% } %>
    </tbody>
</table>

<ul class="pagination">
    <% for (var a = 1; a <= pages; a++) { %>
    <li>
        <a href="?page=<%= a; %>">
            <%= a; %>
        </a>
    </li>
    <% } %>
</ul>

You can run the project from browser by accessing the URL: http://localhost:3000/ and you will see 2 pages on first page along with pagination links at the bottom. On clicking other page link, you will see further records.

Leave a Reply

Please disable your adblocker or whitelist this site!