Reputation: 238
I've implemented pagination into my controller file
exports.products = async (req, res) => {
const pagination = req.query.pagination ? parseInt(req.query.pagination) : 5;
const page = req.query.page ? parseInt(req.query.page) : 1;
const prod = await Product.find({})
.skip((page - 1) * pagination)
.limit(pagination);
res.render("products", {
productsList: prod,
});
};
The code above works, I can access 5 results per page by changing the URL from /products?page=1
to /products?page=2
etc. but I haven't been able to find any information/tutorials that include how to implement the 'next page' links. What I mean is if I have 20 products and want to display 5 products per page, how can I make sure there won't be more than 4 'next page' links at the bottom. Do I have to calculate the number of pages inside my controller and pass that as a variable to my ejs and display the correct amount of links?
I'm just trying to make sure I take the correct approach to this with scaling in mind since I'm relatively new to this! Any help is appreciated
Upvotes: 0
Views: 600
Reputation: 492
it is good you alreade return the product inside some object. you can use it to also return a count:
res.render("products", {
productsList: prod,
count: await Product.count({})
});
devided by 'pagination' is the page count.
Upvotes: 1