Skip to content

Pagination using Node.js and MongoDB

A huge set of data can be split into a series of related pages by Pagination and only one page can be loaded and viewed at a time. If you are building an API with Node.js and MongoDB, this tutorial will be really helpful if you want to browse the data by navigating through pages through pagination. This tutorial covers the backend pagination with Node.js and MongoDB.

Let’s assume you’ve already built an API that returns huge data on invocation and you’d like to implement pagination over it.

Step 1: Pass the current page number and the size of the page to the API.

http://localhost:3300/api/orders?state=KA&pageNo=1&size=10

Step 2: Get the values from the request in repository class.

 var pageNo = parseInt(req.query.pageNo)
 var size = parseInt(req.query.size) 

Step 3: Calculate skip and limit with page number and size. Assign to a JSON Object.

var query = {}
query.skip = size * (pageNo - 1)
query.limit = size

Step 4: Pass the query into the find() method

MongoClient.connect(con, function (err, db) {
        if (err) throw err
        //Condition = filters
        //query = pagination parameters.
        db.collection('orders').find(condition, query).toArray(function (err, result) {
          // console.log(result);
          if (err) throw err
          res.send(result);
        })
  })

If you want to validate if page number, you can try something like this.

 if(pageNo < 0 || pageNo === 0) {
        response = {"error" : true,"message" : "Invalid page, should start with 1"};
        return res.json(response)
 }

Step 5: Publish the changes and test the API.

Hit the URL of your API and test if pagination works.

Sample URL : http://localhost:3300/api/orders?state=DL&pageNo=0&size=10

See also  How to return only specific fields from a MongoDB query?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.