Implementing pagination controller in Node.js | Hindi tutorial on Node.js

Posted by


To create a pagination controller in Node.js, you will need to use libraries such as Express.js and Mongoose for interacting with MongoDB. Pagination allows you to break down a large set of data into multiple pages, making it easier for users to navigate through the data. In this tutorial, we will be writing a sample pagination controller using Node.js and Express.js.

Step 1: Create a new Node.js project
First, you need to create a new Node.js project by running the following command in your terminal:

mkdir pagination-nodejs
cd pagination-nodejs
npm init -y

Step 2: Install the required dependencies
Next, you need to install the required dependencies, which include Express.js and Mongoose. Run the following command in your terminal:

npm install express mongoose

Step 3: Set up Express.js server
Create a new file called app.js and paste the following code:

const express = require('express');
const app = express();

app.use(express.json());

app.listen(3000, () => {
  console.log(`Server is running on port 3000`);
});

Step 4: Connect to MongoDB
Create a new file called db.js and paste the following code to connect to MongoDB:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/pagination', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
.then(() => {
  console.log('Connected to MongoDB');
})
.catch((error) => {
  console.log('Error connecting to MongoDB', error);
});

Step 5: Create a model
Create a new file called model.js and paste the following code to create a sample model:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
});

const User = mongoose.model('User', userSchema);

module.exports = User;

Step 6: Create a pagination controller
Create a new file called paginationController.js and paste the following code:

const User = require('./model');

const getPaginatedUsers = async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;

  const startIndex = (page - 1) * limit;
  const endIndex = page * limit;

  const results = {};

  if (endIndex < await User.countDocuments().exec()) {
    results.next = {
      page: page + 1,
      limit: limit,
    };
  }

  if (startIndex > 0) {
    results.previous = {
      page: page - 1,
      limit: limit,
    };
  }

  results.results = await User.find().limit(limit).skip(startIndex).exec();

  res.json(results);
};

module.exports = { getPaginatedUsers };

Step 7: Update app.js
Update the app.js file to include the pagination controller:

const express = require('express');
const app = express();
const { getPaginatedUsers } = require('./paginationController');
require('./db');

app.use(express.json());

app.get('/users', getPaginatedUsers);

app.listen(3000, () => {
  console.log(`Server is running on port 3000`);
});

Step 8: Run the server
Run the following command in your terminal to start the server:

node app.js

You can now access the pagination API by visiting http://localhost:3000/users?page=1&limit=10. This will return the first page of users with a limit of 10 users per page. You can customize the page and limit parameters to navigate through the data.

This concludes the tutorial on creating a pagination controller in Node.js using Express.js and Mongoose. Pagination is a useful feature for handling large sets of data and improving the user experience. Feel free to customize the code to suit your specific requirements. Happy coding!

0 0 votes
Article Rating

Leave a Reply

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@sabasahilmalik1471
2 hours ago

Plz figma desgion ki project banana sekhyn simple tarika sy i need you help plzzzzz

@sabasahilmalik1471
2 hours ago

Plese figma me project banana sekhyn jaldi sy

@sabasahilmalik1471
2 hours ago

Auth banana sekhyn but simple

@sabasahilmalik1471
2 hours ago

Please ek request h governor house ki q2 ki project banana sekhyn

@MossadTouch
2 hours ago

Sir Ap Ki next.Js14 wali dakhnay say pahlay next.js 13 dakho sir guide karay kay mujhay next.js bilkul nahi ati to apki next.Js ki playlist first video say konsi video tak dekho ❤ please sir guide

5
0
Would love your thoughts, please comment.x
()
x