How to Create Pagination in Node.js using Skip and Limit ?
Last Updated :
18 Jun, 2024
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 method. This allows the client to fetch data in pages. This is achieved by using options skip and limit, giving clients full control of the page(data) they are getting back.
Prerequisites:
When to use Pagination?
As its statement describes, Pagination should be used:
- When clients should have the control of data they are getting back.
- Improving User Experience(UX) and Better Navigation.
Steps to SetUp Project
Step 1: Create a new folder for a project using the following command:
mkdir pagination
Step 2: Navigate to our folder using the following command:
cd pagination
Step 3: Initialize npm using the following command and server file:
npm init -y
touch index.js
Step 4: Install required packages using the following command:
npm i express mongoose
Project Structure:
It will look like the following

Example 1: Without Using Pagination
Node
// index.js
// Requiring module
const express = require('express');
const mongoose = require('mongoose');
const port = 3000;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// Database URL
const MONGODB_URL = 'mongodb://127.0.0.1/pagination';
// Connecting Database through mongoose(ORM For Mongodb)
mongoose
.connect(MONGODB_URL, {
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => {
console.log('Database connected');
})
.catch((err) => {
console.log('Error in connecting database');
});
// Creating Schema for Posts, then it will
// be used in creating Model
const PostSchema = new mongoose.Schema({
name: String,
date: {
type: Date,
default: Date.now(),
},
});
const postModel = new mongoose.model('PostModel', PostSchema);
// For creating Posts
app.post('/', async (req, res) => {
const post = new postModel(req.body);
await post.save();
res.status(201).send('Successfully created');
});
// For Fetching Post
app.get('/', async (req, res) => {
try {
const posts = await postModel.find();
res.status(200).send(posts);
} catch (e) {
console.log(e);
}
});
// Starting the server
app.listen(port, () => {
console.log(`Started at ${port}`);
});
Run the server using the following command:
node index.js
Inserting into Database: Data is inserted with the help of Postman through the following method:
Inserting Database by making a post request into '/' path through Postman.Output: Without Pagination
Fetching Data through Postman without using Pagination.As it could be seen in the above example, Without pagination all the documents will get fetched. To be more clear about the use and need of Pagination. Think of this case when there are thousands of documents rather than just 4.
Example 2: With Using Pagination
For Pagination skip and limit, parameters will be used using the limit and skip method along with find.
Node
// index.js
// Requiring module
const express = require('express');
const mongoose = require('mongoose');
const port = 3000;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// Database URL
const MONGODB_URL = 'mongodb://127.0.0.1/pagination';
// Connecting Database through mongoose(ORM For Mongodb)
mongoose
.connect(MONGODB_URL, {
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => {
console.log('Database connected');
})
.catch((err) => {
console.log('Error in connecting database');
});
// Creating Schema for Posts, then it will
// be used in creating Model
const PostSchema = new mongoose.Schema({
name: String,
date: {
type: Date,
default: Date.now(),
},
});
const postModel = new mongoose.model('PostModel', PostSchema);
// For creating Posts
app.post('/', async (req, res) => {
const post = new postModel(req.body);
await post.save();
res.status(201).send('Successfully created');
});
// For Fetching Post
app.get('/', async (req, res) => {
try {
// Adding Pagination
const limitValue = req.query.limit || 2;
const skipValue = req.query.skip || 0;
const posts = await postModel.find()
.limit(limitValue).skip(skipValue);
res.status(200).send(posts);
} catch (e) {
console.log(e);
}
});
// Starting the server
app.listen(port, () => {
console.log(`Started at ${port}`);
});
Step to Run:Run the server using the following command:
node index.js
Output: With Pagination
Pagination with limit=2 and skip=0 returns the first 2 documents,
Similar Reads
How to Perform a Find Operation with Limit and Skip in MongoDB using Node.js?
In MongoDB, the find operation is used to query the database and retrieve documents that match a specified criterion. Using limit and skip along with find allows for efficient pagination of results. limit specifies the maximum number of documents to return, while skip specifies the number of documen
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 make a Pagination using HTML and CSS ?
Creating pagination is quite simple, you can easily do that by using Bootstrap, and JavaScript. However, in this article, we will use HTML and CSS to create pagination. Pagination is helpful when the website contains lots of content on a single page, and a single page will not look good with all th
3 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 a
8 min read
Pagination using Node, Mongo, Express.js and EJS
In this article, we will dive into the process of implementing pagination in our web application using NodeJS, MongoDB, Express, and EJS for dynamic HTML rendering. Additionally, we'll enhance the visual appeal of our pagination controls with CSS. Our focus will be on creating a user profile system
4 min read
Create a Pagination using HTML CSS and JavaScript
In this article, we will create a working pagination using HTML, CSS, and JavaScript. Pagination, a widely employed user interface pattern, serves the purpose of dividing extensive data or content into more manageable portions. It allows users the ability to effortleÂssly navigate through numerou
5 min read
How to Create Indexes in MongoDB using Node.js?
MongoDB, a popular NoSQL database, provides powerful indexing capabilities to improve query performance. Indexes in MongoDB help in quickly locating documents and speeding up read operations. In this tutorial, we'll explore how to create indexes in MongoDB using Node.js. What is an Index in MongoDB?
3 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 Add Hoverable Pagination using CSS ?
Pagination is a common technique for controlling content that covers multiple pages. Hoverable pagination provides a sleek alternative to traditional pagination styles by enabling users to preview the content without clicking by hovering over the pagination elements. Traditional pagination styles re
2 min read
How to we create Pagination in Materialize CSS ?
Materialize CSS is a front-end UI library that is created by Google using the combination of HTML, CSS, and JavaScript. It is basically a design language that combines classic design along with modern innovations and technology. The purpose of Google behind developing Materialize CSS is to provide a
3 min read