server side pagination with nodejs and mongodb

While developing web application there may be situation where we have millions of data and we need to show the data with limited data at once. So for handling such situation we use serverside pagination, So now we are going to discuss the same while using nodejs and monodb at backend.

 

So let's have a look on our code(server.js),

 

 
let express = require('express'),
    mongoose = require('mongoose');
let Coin = require('./coins');
       mongoose.connect('mongodb://localhost:27017/worldcoindata_live', function(err, db) {
           if(err) throw err;
           console.log('database connected successfully');
       });
       var app = express();
       app.get('/', function(req, res) {
           res.send('<h3>welcome to server side pagination demo</h3><br><h3>Enter any url containing <b>/coins/page_no/per_page</b></h3>');
       });
       app.get('/coins/:page/:perPage', function(req, res) {
           console.log('page number : ' + req.params.page); 
           console.log('per page : ' + req.params.perPage);
           var pageNo = req.params.page ; // parseInt(req.query.pageNo)
           var size = req.params.perPage;
           var query = {}
           if (pageNo < 0 || pageNo === 0) {
               response = { "error": true, "message": "invalid page number, should start with 1" };
               return res.json(response)
           }
           query.skip = size * (pageNo - 1)
           query.limit = parseInt(size)
           // Find some documents
           Coin.find({}, {}, query, function (err, data) {
               // Mongo command to fetch all data from collection.
               if (err) {
                   response = { "error": true, "message": "Error fetching data" };
               } else {
                   response = { "error": false, "message": data };
               }
               res.json(response);
           });
       });
       app.listen(3000, function(req, res) {
           console.log('server started on port : 3000');
       });
 

 

In the above code we have created app with express and then created connection with data using mongoose. After that we have fetched the current page of data so that data for the page can be fetched accordingly. And after finding the current page and size of the record we passed that data into mongoose model so that data can be fetched accordingly. 

After installing all the dependencies of the app, start the application with node server.js and type http://localhost:3000/coins/1/20. 

We will get data on the page like below

Pretty cool! Finally, our task completes here.

That’s all for now. Thank you for reading and I hope this post will be very helpful.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

You can download complete code from here. Download Code