How to do Pagination in Node.js using Sorting Ids ?
Last Updated :
13 Jun, 2024
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
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:
Similar Reads
How to Create Pagination in Node.js using Skip and Limit ?
Creating pagination in Node.js using the skip and limit methods. This approach efficiently retrieves specific data subsets from a database, improving performance and user experience by loading content in manageable segments rather than all at once. What is Pagination?Pagination is a very helpful met
4 min read
How to do pagination Node.js with MySQL ?
Node.js is a runtime environment like Chrome's V8 JavaScript engine. Node.js is an open-source, cross-platform, and backend runtime environment that executes outside a web browser. MySQL is an open-source relational database management system that is fast, reliable, flexible, and robust. Both MySQL
9 min read
How To Perform a Find Operation With Sorting In MongoDB Using Node.js?
Performing a find operation with sorting in MongoDB using Node.js is a common task for developers working with databases. This guide will walk you through the process step-by-step, including setting up a MongoDB database, connecting to it using Node.js, performing a find operation, and sorting the r
3 min read
How to implement pagination in React using Hooks?
Implementing pagination in React using hooks involves managing the state of the current page and the number of items per page, as well as rendering the paginated data accordingly. Implementing pagination in React using Hooks:Setup Initial State: Use the useState hook to manage the state for the curr
3 min read
How to add Pagination in Nextjs using Algolia ?
Adding pagination to a Next.js application with Algolia involves fetching and displaying paginated search results from Algoliaâs API. This setup provides an efficient way to handle large datasets by loading data in chunks. In this article, we will learn How we can add pagination in the NextJS projec
2 min read
How To Do Pagination In Python
In this article, we'll walk you through the steps of setting up pagination in Python. We'll explain each step clearly and straightforwardly. To help you understand the idea of pagination in Python, we'll show you how to create a pagination system using the Tkinter library. We'll start by explaining
5 min read
How to Customize Pagination in Next.js ?
In this article, we will learn How we can add customized pagination in the NextJS project using Algolia. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering you
3 min read
How to Perform Aggregation Operations in MongoDB using Node.js?
Aggregation operations in MongoDB allow you to process data records and return computed results. These operations group values from multiple documents, and perform a variety of operations on the grouped data to return a single result. MongoDB's aggregation framework is powerful and flexible, enablin
3 min read
How to sorting an array without using loops in Node.js ?
The setInterval() method repeats or re-schedules the given function at every given time-interval. It is somewhat like window.setInterval() Method of JavaScript API, however, a string of code can't be passed to get it executed. Syntax: setInterval(timerFunction, millisecondsTime); Parameter: It accep
2 min read
How to use Pagination Component in ReactJS ?
Pagination is a feature through which users can easily switch between pages across a website or app. With the help of this component, a user can select a specific page from a range of pages. Material UI for React has this component available for us, and it is very easy to integrate. We can use the f
2 min read