Skip to content

Commit b1e856c

Browse files
committed
pagination for get all plants controller added
1 parent 001d2d6 commit b1e856c

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

Backend/controllers/plantController.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,10 @@ exports.getAllPlants = async (req, res) => {
2222
// console.log(JSON.parse(queryString));
2323
// mongoose {tag:'Indoor' , price:{$gte:200}}
2424
// req.query { tag: 'Indoor', price: { gte: '200' } }
25+
let query = Plant.find(JSON.parse(queryString));
2526

2627
// 2) Sorting
2728

28-
let query = Plant.find(JSON.parse(queryString));
29-
3029
if (req.query.sort) {
3130
//mongoose sort('price ratingsAverage)
3231

@@ -45,6 +44,18 @@ exports.getAllPlants = async (req, res) => {
4544
query = query.select('-__v');
4645
}
4746

47+
// 4) Pagination
48+
const page = req.query.page * 1 || 1;
49+
const limit = req.query.limit * 1 || 12;
50+
const skip = (page - 1) * limit;
51+
// page=2&limit=10 , 1-10 , page-1 , 11-20 , page-2
52+
query = query.skip(skip).limit(limit);
53+
54+
if (req.query.page) {
55+
const numPlants = await Plant.countDocuments();
56+
if (skip >= numPlants) throw new Error('This page does not exist');
57+
}
58+
4859
// EXECUTE QUERY
4960

5061
const plants = await query;

0 commit comments

Comments
 (0)