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 }); }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter