How to create pagination in Node.js using skip and limit ? - GeeksforGeeks

10 Jun, 2021
Nodejs is an open-source and cross-platform runtime environment for executing JavaScript code outside the browser. It is widely used in developing APIs and microservices from small to large companies. It is a great tool as this enables developers to use JavaScript both on the server and client sides.
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: Basic knowledge of Nodejs and Mongodb.
 
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.
Creating a 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
index.js
// Requiring moduleconst express = require('express');const mongoose = require('mongoose');const port = 3000;const app = express();  app.use(express.json());app.use(express.urlencoded({ extended: false }));  // Database URLconst 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 Modelconst PostSchema = new mongoose.Schema({    name: String,    date: {        type: Date,        default: Date.now(),    },});  const postModel = new mongoose.model('PostModel', PostSchema);  // For creating Postsapp.post('/', async (req, res) => {    const post = new postModel(req.body);    await post.save();    res.status(201).send('Successfully created');});  // For Fetching Postapp.get('/', async (req, res) => {    try {        const posts = await postModel.find();        res.status(200).send(posts);    } catch (e) {        console.log(e);    }});  // Starting the serverapp.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.
index.js
// Requiring moduleconst express = require('express');const mongoose = require('mongoose');const port = 3000;const app = express();  app.use(express.json());app.use(express.urlencoded({ extended: false }));  // Database URLconst 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 Modelconst PostSchema = new mongoose.Schema({    name: String,    date: {        type: Date,        default: Date.now(),    },});  const postModel = new mongoose.model('PostModel', PostSchema);  // For creating Postsapp.post('/', async (req, res) => {    const post = new postModel(req.body);    await post.save();    res.status(201).send('Successfully created');});  // For Fetching Postapp.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 serverapp.listen(port, () => {    console.log(`Started at ${port}`);});
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,
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.
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript