We are using React first for our front end...
countDocument - It will count how many documents we actually have,
skip() - We can skip a certain amount of items with the skip method and there, I calculate the current page minus
limit() - It will limit our page.
const currentPage = req.query.page || 1; const perPage = 2; let totalItems; Post.find() .countDocuments() .then(count => { totalItems = count; return Post.find() .skip((currentPage - 1) * perPage) .limit(perPage); }) .then(posts => { res .status(200) .json({ message: 'Fetched posts successfully.', posts: posts, totalItems: totalItems }); }) .catch(err => { if (!err.statusCode) { err.statusCode = 500; } next(err); }); };
Comments