How to create pagination in Node.js using skip and limit ?
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.
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 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:
Output: Without 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 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}`); }); |
Run the server using the following command:
node index.js
Output: With Pagination