How to do pagination in Node.js using sorting ids ?
Pagination in NodeJS is defined as adding the numbers to identify the sequential number of the pages. In pagination, we used to skip and limit for reducing the size of data in the database when they are very large in numbers. In this article, we will do pagination in NodeJS using sorting IDs.
Approach: Sorting in the NodeJS helps to sort the result in ascending or descending order. We use the sort() method in which we pass one parameter that results in ascending or descending order. Use the value -1 in the sort object to sort descending and 1 to sort the object in the ascending order.
Installing module: You can install the required module using the following command.
npm install mongoose
npm install express
npm install bcryptjs
npm install body-parser
Project Structure: It will look like this.
MongoDB Database: Following is the sample data stored in your database for this example.
Method 1: Sorting in ascending order using IDs.
user.js
var mongoose = require( "mongoose" );
var userSchema = new mongoose.Schema({
username:String,
password:String
});
module.exports = mongoose.model( "User" ,userSchema);
|
app.js
var express = require( 'express' ),
Mongoose = require( 'mongoose' ),
Bcrypt = require( 'bcryptjs' ),
bodyParser = require( 'body-parser' ),
jsonParser = bodyParser.json(),
User = require( './user' )
const app = express();
const db = `mongodb+srv:
cluster0.k0sop.mongodb.net/user?retryWrites=
true &w=majority`
Mongoose.connect(db, {
useNewUrlParser: true ,
useUnifiedTopology: true ,
useCreateIndex: true
}).then(() => console.log( 'MongoDB Connected....' ))
app.get( "/send" , async (req, res, next) => {
try {
let { page, size, sort } = req.query;
if (!page) {
page = 1;
}
if (!size) {
size = 10;
}
const limit = parseInt(size);
const user = await User.find().sort(
{ votes: 1, _id: 1 }).limit(limit)
res.send({
page,
size,
Info: user,
});
}
catch (error) {
res.sendStatus(500);
}
});
app.post( '/send' , jsonParser, (req, res) => {
req.body.password =
Bcrypt.hashSync(req.body.password, 10);
var newUser = new User({
username: req.body.username,
password: req.body.password,
})
newUser.save()
.then(result => {
console.log(result);
});
})
app.listen(3000, function () {
console.log( "Express Started on Port 3000" );
});
|
Run app.js file using the following command:
node app.js
Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output:
Method 2: Sorting in descending order using IDs
user.js
var mongoose = require( "mongoose" );
var userSchema = new mongoose.Schema({
username:String,
password:String
});
module.exports = mongoose.model( "User" , userSchema);
|
app.js
var express = require( 'express' ),
Mongoose = require( 'mongoose' ),
Bcrypt = require( 'bcryptjs' ),
bodyParser = require( 'body-parser' ),
jsonParser = bodyParser.json(),
User = require( './user' )
const app = express();
const db = `mongodb+srv:
@cluster0.k0sop.mongodb.net/user?
retryWrites= true &w=majority`
Mongoose.connect(db, {
useNewUrlParser: true ,
useUnifiedTopology: true ,
useCreateIndex: true
}).then(() => console.log( 'MongoDB Connected....' ))
app.get( "/send" , async (req, res, next) => {
try {
let { page, size, sort } = req.query;
if (!page) {
page = 1;
}
if (!size) {
size = 10;
}
const limit = parseInt(size);
const user = await User.find().sort(
{ votes: 1, _id: -1 }).limit(limit)
res.send({
page,
size,
Info: user,
});
}
catch (error) {
res.sendStatus(500);
}
});
app.post( '/send' , jsonParser, (req, res) => {
req.body.password =
Bcrypt.hashSync(req.body.password, 10);
var newUser = new User({
username: req.body.username,
password: req.body.password,
})
newUser.
save()
.then(result => {
console.log(result);
});
})
app.listen(3000, function () {
console.log( "Express Started on Port 3000" );
});
|
Run app.js file using the following command:
node app.js
Output: Now open your browser and go to http://localhost:3000/send?sort, you will see the following output:
Last Updated :
21 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...