Best way to paginate with Mongoose and Node.js
I am currently studying mongoose and I am building a pagination system. I made two codes, but I am wondering which one is the best way to do what I want in terms of performance and everything.
Script 1:
app.get("/:page",(req,res)=>{
post.find({}).then((data)=>{
let per_page = 2; // set how many posts per page
let num_page = Number(req.params.page);
let max_pages = Math.ceil(data.length/per_page);
if(num_page == 0 || num_page > max_pages){
res.render('404');
}else{
let starting = per_page*(num_page-1)
let ending = per_page+starting
res.render('posts', {posts:data.slice(starting,ending), pages: max_pages, current_page: num_page});
}
});
});
Script 2:
app.get("/:page",(req,res)=>{
post.count({}, (err, len)=>{
let per_page = 2; // set how many posts per page
let num_page = Number(req.params.page);
let max_pages = Math.ceil(len/per_page);
if(num_page == 0 || num_page > max_pages){
res.render('404');
}else{
let starting = per_page*(num_page-1);
let ending = per_page+starting;
let promise = post.find({}).limit(per_page).skip(starting);
promise.then((data)=>{
res.render('posts', {posts:data, pages: max_pages, current_page: num_page});
});
}
});
});
+3
source to share
No one has answered this question yet
See similar questions:
or similar: