Skip to content

Commit c7deea3

Browse files
committed
Nodejs MongoDB Pagination Example
1 parent af30b00 commit c7deea3

File tree

7 files changed

+823
-0
lines changed

7 files changed

+823
-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.esvi3.mongodb.net/loizenaidb'
3+
}
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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+
address: req.body.address,
11+
});
12+
13+
// Save a Customer in the MongoDB
14+
customer.save().then(data => {
15+
// send uploading message to client
16+
res.status(200).json({
17+
message: "Upload Successfully a Customer to MongoDB with id = " + data.id,
18+
customer: data,
19+
});
20+
}).catch(err => {
21+
res.status(500).json({
22+
message: "Fail!",
23+
error: err.message
24+
});
25+
});
26+
};
27+
28+
exports.filteringByAge = (req, res) => {
29+
const age = parseInt(req.query.age);
30+
31+
Customer.find({age:age}).select("-__v")
32+
.then(results => {
33+
res.status(200).json({
34+
"message": "Get all Customers with age = " + age,
35+
"size": results.length,
36+
"customers": results
37+
});
38+
}).catch(err => {
39+
console.log(err);
40+
res.status(500).json({
41+
message: "Error!",
42+
error: err
43+
});
44+
});
45+
}
46+
47+
exports.pagination = async (req, res) => {
48+
49+
try {
50+
51+
const page = parseInt(req.query.page);
52+
const limit = parseInt(req.query.limit); // Make sure to parse the limit to number
53+
54+
const offset = page ? page * limit : 0;
55+
56+
// We are using the '3 layer' architecture explored on the 'bulletproof node.js architecture'
57+
// Basically, it's just a class where we have our business logic
58+
59+
let results = await Customer.find({}) // You may want to add a query
60+
.skip(offset) // Always apply 'skip' before 'limit'
61+
.limit(limit)
62+
.select("-__v"); // This is your 'page size'
63+
64+
let numOfCustomer = await Customer.countDocuments({});
65+
66+
res.status(200).json({
67+
"message": "Paginating is completed! Query parameters: page = " + page + ", limit = " + limit,
68+
"totalPages": Math.ceil(numOfCustomer / limit),
69+
"totalItems": numOfCustomer,
70+
"limit": limit,
71+
"currentPageSize": results.length,
72+
"customers": results
73+
});
74+
} catch (error) {
75+
res.status(500).send({
76+
message: "Error -> Can NOT complete a paging request!",
77+
error: error.message,
78+
});
79+
}
80+
81+
}
82+
83+
exports.pagination_v2 = async (req, res) => {
84+
85+
try {
86+
87+
const page = parseInt(req.query.page);
88+
const limit = parseInt(req.query.limit); // Make sure to parse the limit to number
89+
90+
const offset = page ? page * limit : 0;
91+
92+
// We are using the '3 layer' architecture explored on the 'bulletproof node.js architecture'
93+
// Basically, it's just a class where we have our business logic
94+
95+
let results = await Customer.aggregate([
96+
{ $match: {} }, // This is your query
97+
{ $skip: offset }, // Always apply 'skip' before 'limit'
98+
{ $limit: limit }, // This is your 'page size'
99+
]).select("-__v")
100+
101+
let numOfCustomer = await Customer.countDocuments({});
102+
103+
res.status(200).json({
104+
"message": "Paginating is completed! Query parameters: page = " + page + ", limit = " + limit,
105+
"totalPages": Math.ceil(numOfCustomer / limit),
106+
"totalItems": numOfCustomer,
107+
"limit": limit,
108+
"currentPageSize": results.length,
109+
"customers": results
110+
});
111+
} catch (error) {
112+
res.status(500).send({
113+
message: "Error -> Can NOT complete a paging request!",
114+
error: error.message,
115+
});
116+
}
117+
118+
}
119+
120+
exports.paginationfilterandsort = async (req, res) => {
121+
try {
122+
const page = parseInt(req.query.page);
123+
const limit = parseInt(req.query.limit); // Make sure to parse the limit to number
124+
const age = parseInt(req.query.age);
125+
126+
const offset = page ? page * limit : 0;
127+
128+
let results = await Customer.find({age: age}) // You may want to add a query
129+
.skip(offset) // Always apply 'skip' before 'limit'
130+
.limit(limit)
131+
.sort({"firstname": 1, "lastname": -1})
132+
.select("-__v"); // This is your 'page size'
133+
134+
let numOfCustomer = await Customer.countDocuments({age: age});
135+
136+
res.status(200).json({
137+
"message": "Paginating is completed! Query parameters: page = " + page + ", limit = " + limit,
138+
"totalPages": Math.ceil(numOfCustomer / limit),
139+
"totalItems": numOfCustomer,
140+
"limit": limit,
141+
"age-filtering": age,
142+
"currentPageSize": results.length,
143+
"customers": results
144+
});
145+
} catch (error) {
146+
res.status(500).send({
147+
message: "Error -> Can NOT complete a paging + filtering + sorting request!",
148+
error: error.message,
149+
});
150+
}
151+
};
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const mongoose = require('mongoose');
2+
3+
const CustomerSchema = mongoose.Schema({
4+
firstname: String,
5+
lastname: String,
6+
address: String,
7+
age: {
8+
type: Number,
9+
min: 18,
10+
max: 65,
11+
required: true
12+
},
13+
copyrightby: {
14+
type: String,
15+
default: 'https://loizenai.com'
16+
}
17+
});
18+
19+
module.exports = mongoose.model('Customer', CustomerSchema);
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
module.exports = function(app) {
2+
3+
var customers = require('../controllers/customer.controller.js');
4+
5+
// Create a new Customer
6+
app.post('/api/customer/create', customers.create);
7+
8+
app.get('/api/customer/filteringbyage', customers.filteringByAge);
9+
10+
app.get('/api/customer/pagination', customers.pagination);
11+
app.get('/api/customer/pagination_v2', customers.pagination);
12+
13+
app.get('/api/customer/pagefiltersort', customers.paginationfilterandsort);
14+
}

0 commit comments

Comments
 (0)