pagination backend
Mon Jul 18 2022 20:50:42 GMT+0000 (UTC)
Saved by
@gazifahad
#javascript
#nodejs
#jwt
#login
const {page}=req.query;
console.log(page);
try {
const LIMIT=6;
// limit can be used dynamically
const startIndex=(Number(page)-1 )* LIMIT;//getting the starting index of all the posts
// converting page to Number because we get string as query
const total=await PostMessage.countDocuments({});
const posts = await PostMessage.find().sort({_id:-1}).limit(LIMIT).skip(startIndex); //skipping all the previous pages from loading
res.status(200).json({data:posts,currentPage:Number(page),numberOfPages:Math.ceil(total/LIMIT)});
}
catch (error) {
res.status(404).json({ message: error.message });
}
content_copyCOPY
Comments