How to do pagination in Node.js using sorting ids ?

21 Jun, 2021
Pagination in NodeJS is defined as adding the numbers to identify the sequential number of the pages. In pagination, we used to skip and limit for reducing the size of data in the database when they are very large in numbers. In this article, we will do pagination in NodeJS using sorting IDs.
Approach: Sorting in the NodeJS helps to sort the result 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.
Installing module: You can install the required module using the following command. 
npm install mongoose 
npm install express 
npm install bcryptjs 
npm install body-parser
Project Structure: It will look like this.
MongoDB Database: Following is the sample data stored in your database for this example.
Method 1: Sorting in ascending order using IDs.
user.js
var mongoose = require("mongoose");  var userSchema = new mongoose.Schema({    username:String,    password:String});  module.exports = mongoose.model("User",userSchema);
app.js
var 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 Requestapp.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 Requestapp.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 setupapp.listen(3000, function () {    console.log("Express Started on Port 3000");});
Run app.js file using the following command:
node app.js
Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output:
Method 2: Sorting in descending order using IDs
user.js
var mongoose = require("mongoose");  var userSchema = new mongoose.Schema({    username:String,    password:String});  module.exports = mongoose.model("User", userSchema);
app.js
var 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 Requestapp.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 Requestapp.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 setupapp.listen(3000, function () {    console.log("Express Started on Port 3000");});
Run app.js file using the following command:
node app.js
Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output:
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React