Skip to content

Commit ee39933

Browse files
committed
Nodejs MongoDB Pagination - Backend Server Side Pagination
1 parent c7deea3 commit ee39933

File tree

7 files changed

+829
-0
lines changed

7 files changed

+829
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = {
2+
url: 'mongodb+srv://loizenai:loizenai@cluster0.gmd7e.mongodb.net/loizenaidb?retryWrites=true&w=majority'
3+
}
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
const Customer = require('../models/customer.model.js');
2+
3+
// POST a Customer
4+
exports.create = (req, res) => {
5+
6+
const customer = new Customer({
7+
firstname: req.body.firstname,
8+
lastname: req.body.lastname,
9+
age: req.body.age,
10+
salary: req.body.salary,
11+
address: req.body.address,
12+
});
13+
14+
// Save a Customer in the MongoDB
15+
customer.save().then(data => {
16+
// send uploading message to client
17+
res.status(200).json({
18+
message: "Upload Successfully a Customer to MongoDB with id = " + data.id,
19+
customer: data,
20+
});
21+
}).catch(err => {
22+
res.status(500).json({
23+
message: "Fail!",
24+
error: err.message
25+
});
26+
});
27+
};
28+
29+
exports.getSalaries = (req, res) => {
30+
try {
31+
Customer.find({}).distinct("salary")
32+
.then(result => {
33+
let salaries = result.sort(function(a, b){return b - a});
34+
res.send(salaries);
35+
});
36+
} catch (error) {
37+
res.status(500).send({
38+
message: "Error -> Can NOT get all customer's salaries",
39+
error: error.message
40+
});
41+
}
42+
}
43+
44+
exports.paginationfilterandsort = async (req, res) => {
45+
try {
46+
let page = parseInt(req.query.page);
47+
let limit = parseInt(req.query.size);
48+
let agesorting = (req.query.agesorting === 'true');
49+
let desc = (req.query.desc === 'true');
50+
let salary = req.query.salary ? parseInt(req.query.salary) : -1;
51+
52+
const offset = page ? page * limit : 0;
53+
54+
console.log("offset = " + offset);
55+
56+
let result = {};
57+
let numOfCustomer;
58+
59+
// NOT Filtering with salary
60+
if(salary < 0){
61+
numOfCustomer = await Customer.countDocuments({});
62+
// not sorting with age
63+
if(agesorting == false) {
64+
result = await Customer.find({}) // You may want to add a query
65+
.skip(offset) // Always apply 'skip' before 'limit'
66+
.limit(limit)
67+
.select("-__v"); // This is your 'page size'
68+
} else {
69+
if(desc == false) { // sorting with age and ascending
70+
result = await Customer.find({}) // You may want to add a query
71+
.skip(offset) // Always apply 'skip' before 'limit'
72+
.limit(limit)
73+
.sort({"age": 1})
74+
.select("-__v"); // This is your 'page size'
75+
} else { // sorting with age and descending
76+
result = await Customer.find({}) // You may want to add a query
77+
.skip(offset) // Always apply 'skip' before 'limit'
78+
.limit(limit)
79+
.sort({"age": -1})
80+
.select("-__v"); // This is your 'page size'
81+
}
82+
}
83+
} else { // Filtering with salary
84+
85+
numOfCustomer = await Customer.countDocuments({salary: salary});
86+
// not sorting with age
87+
if(agesorting == false) {
88+
if(desc == false) { // sorting with age and ascending
89+
result = await Customer.find({salary: salary}) // You may want to add a query
90+
.skip(offset) // Always apply 'skip' before 'limit'
91+
.limit(limit)
92+
.select("-__v"); // This is your 'page size'
93+
}
94+
} else {
95+
if(desc == false) { // sorting with age and ascending
96+
result = await Customer.find({salary: salary}) // You may want to add a query
97+
.skip(offset) // Always apply 'skip' before 'limit'
98+
.limit(limit)
99+
.sort({"age": 1})
100+
.select("-__v"); // This is your 'page size'
101+
} else { // sorting with age and descending
102+
result = await Customer.find({salary: salary}) // You may want to add a query
103+
.skip(offset) // Always apply 'skip' before 'limit'
104+
.limit(limit)
105+
.sort({"age": -1})
106+
.select("-__v"); // This is your 'page size'
107+
}
108+
}
109+
}
110+
111+
const response = {
112+
"copyrightby": "https://loizenai.com",
113+
"totalItems": numOfCustomer,
114+
"totalPages": Math.ceil(numOfCustomer / limit),
115+
"pageNumber": page,
116+
"pageSize": result.length,
117+
"customers": result
118+
};
119+
120+
res.status(200).json(response);
121+
} catch (error) {
122+
res.status(500).send({
123+
message: "Error -> Can NOT complete a paging request!",
124+
error: error.message,
125+
});
126+
}
127+
};
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const mongoose = require('mongoose');
2+
3+
const CustomerSchema = mongoose.Schema({
4+
firstname: String,
5+
lastname: String,
6+
address: String,
7+
salary: {
8+
type: Number,
9+
required: true
10+
},
11+
age: {
12+
type: Number,
13+
min: 18,
14+
max: 65,
15+
required: true
16+
},
17+
copyrightby: {
18+
type: String,
19+
default: 'https://loizenai.com'
20+
}
21+
});
22+
23+
CustomerSchema.virtual('id').get(function(){
24+
return this._id.toHexString();
25+
});
26+
27+
// Ensure virtual fields are serialised.
28+
CustomerSchema.set('toJSON', {
29+
virtuals: true
30+
});
31+
32+
module.exports = mongoose.model('Customer', CustomerSchema);
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module.exports = function(app) {
2+
3+
var customers = require('../controllers/customer.controller.js');
4+
5+
// Create a new Customer
6+
app.post('/api/customers/create', customers.create);
7+
app.get('/api/customers/salaries', customers.getSalaries);
8+
app.get('/api/customers/pagefiltersort', customers.paginationfilterandsort);
9+
}

0 commit comments

Comments
 (0)