Pagination using express and mongoose
Introduction
Hello all, In this article we are going to learn how to apply pagination in Restful api's using mongoose and express.
What is pagination?
Pagination is a technique which divides web content into discrete pages. Good choices about data paging are an important part of design and development. Sometimes we need to get lists of data from the server, and sometimes these lists can be really long. Breaking lists up into smaller, discreet "pages" can reduce server overhead and improve response time.
Without wasting more time , let's get started.
Step:1 - First create a folder with any name (for this tutorial i used folder name pagination
) and open with the vs code. Open the terminal in vs code and run npm init -y
to initialize the project.
Step:2 - Now, install dependencies express and mongoose
npm i express mongoose
Step:3 - Now made a index.js
file in the root directory pagination
and let's made a express server which is pretty simple.
index.js
const express = require("express");
const app = express();
const port = 5000;
app.get("/",(req,res) => {
res.send("server is running")
})
app.listen(port,() => console.log(`listening on port : ${port}`));
Great our server is up and running on localhost:5000.
Step:2 - let's create another file named mongoose.js
and configure our db connection.
const mongoose = require("mongoose");
const initializeDB = async () => {
await mongoose
.connect('mongodb://localhost:27017/myapp', { useCreateIndex:
true,useUnifiedTopology: true, useNewUrlParser:
true,useFindAndModify:false })
.then(() => console.log("DB connected"))
.catch((err) => console.error(err));
};
module.exports = { initializeDB };
Step:3 - Import initializeDB
function from mongoose.js
in index.js
file and call it to connect with mongodb on localhost.
index.js
const express = require("express");
const app = express();
const port = 5000;
const { initializeDB } = require("./mongoose.js");
initializeDB()
app.get("/",(req,res) => {
res.send("server is running")
})
app.listen(port,() => console.log(`listening on port : ${port}`));
Step:4 - let's create another file named user.js
and define schema for users
.
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: String,
age: Number
});
const Users = new mongoose.model("User", UserSchema);
module.exports = Users;
Step:5 - Now let's import user
model from user.js
in index.js
file and make a get
api for the users.
index.js
const express = require("express");
const app = express();
const port = 5000;
const { initializeDB } = require("./mongoose.js");
const Users = require("./user.js");
initializeDB()
app.get("/",(req,res) => {
res.send("server is running")
})
app.get("/users",async(req,res) => {
const users = await Users.find({}); // get all users
res.status(200).json({ users }); // send response to frontend
})
app.listen(port,() => console.log(`listening on port : ${port}`));
Step:6 - This is the final step. In this step we will modify and apply the pagination in the /users
api that we have created in the step 5.
app.get("/users",async(req,res) => {
// define page
let page;
If(req.query.page){
page = parseInt(req.query.page);
}
else{
page = 1;
}
// define limit per page
const limit = 30;
const skip = (page - 1) * limit;
// count total users
const total = await Users.countDocuments({});
const users = await Users.find({}).skip(skip).limit(limit);
res.status(200).json({ users,total }); // send response to frontend
})
That's it
Pretty simple, right? If you have any questions about your implementation, drop them in the comments below . I’m always happy to help!