Skip to main content

Pagination

What is Pagination?

Pagination is a technique to split the data into multiple pages. For example, if you have 10000 records in your database, and you want to display all the records on a single page, then it will take a lot of time to transfer the data from the server to the client. It will also affect the performance of the application. So, we need to use pagination to improve the performance of the application.

So, we can get and display records in chunks. For example, we can display 10 records per page, and the user can navigate between the pages.

What's the need?

Pagination is used to improve the performance of the application. Transferring 10000 records from the server to the client will take a lot of time. So, we need to use pagination to improve the performance of the application.

Pagination is normally used in GET APIs. For example, if you have a GET API (GET /users) to get all the users from the database, then you can use pagination in that API. So, you can display 10 records per page, and the user can navigate between the pages.

Let's get started

First of all, set up the project. Then, we will create a GET API to get all the users from the database, and we will use pagination in that API.

Folder structure

Folder structure
project-folder
├── index.js
├── models
│ └── user.js
└── routes
└── user.js
models/user.js
models/user.js
import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
});

export default mongoose.model("User", userSchema);
routes/user.js
routes/user.js
import express from "express";
import User from "../models/user.js";

const router = express.Router();

router.get("/", async (req, res) => {
const users = await User.find();
res.send(users);
});

router.post("/", async (req, res) => {
const user = await User.create(req.body);
res.send(user);
});

export default router;
index.js
index.js
import express from "express";
import mongoose from "mongoose";
import userRouter from "./routes/user.js";

const app = express();

app.use(express.json());

app.use("/users", userRouter);

mongoose.connect("mongodb://localhost:27017/express-pagination");

app.listen(3000, () => {
console.log("Server started on port 3000");
});

Pagination in GET API

Now, we will do pagination in the GET API. I will take limit and skip query parameters from the request. limit is used to specify the number of records to be displayed per page. And skip is used to specify the number of records to be skipped. This means the client will tell the server how many records it wants to skip, and how many records it wants to display per page.

For example, if you have 1000 records in your database, and you want to display 10 records per page, then you can use the following query parameters.

Query parameters
/users?limit=10&skip=0 => First 10 records (1 - 10)
/users?limit=10&skip=10 => Next 10 records (11 - 20)
/users?limit=10&skip=20 => Next 10 records (21 - 30)
/users?limit=10&skip=30 => Next 10 records (31 - 40)

Normally, we use the find() and aggregate() functions to get the data from the database. So, I will do pagination using both functions.

import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

routes/user.js
router.get("/", async (req, res) => {
// if limit is not provided, then use 10 as default limit
const limit = parseInt(req.query.limit) || 10;
// if skip is not provided, then use 0 as default skip
const skip = parseInt(req.query.skip) || 0;

// get the users from the database, and apply limit, and skip
const users = await User.find().limit(limit).skip(skip);
// get the total number of users in the database
const total = await User.countDocuments();

// send the response
res.send({ users, total });
});
routes/user.js
router.get("/", async (req, res) => {
// if limit is not provided, then use 10 as default limit
const limit = parseInt(req.query.limit) || 10;
// if skip is not provided, then use 0 as default skip
const skip = parseInt(req.query.skip) || 0;

// get the users from the database, and apply the limit and skip
const users = await User.aggregate([
{ $skip: skip },
{ $limit: limit },
]);

// get the total number of users in the database
const total = await User.countDocuments();

// send the response
res.send({ users, total });
});

Conclusion

In this doc, we learned how to do pagination in Express. We used the limit and skip query parameters to do pagination.