How to add pagination in our REST APIs in our backend ?
top of page

How to add pagination in our REST APIs in our backend ?

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); }); };



3 views0 comments

Recent Posts

See All

SQL UNION GROUP BY

SQL UNION Operator UNION operator is used to combine the results of two or more SELECT statements Every SELECT statement within UNION must have the same number of columns The columns must also have si

SQL JOIN

JOIN clause is used to combine rows from two or more tables. INNER JOIN === selects records that have matching values in both tables SELECT Orders.OrderID, Customers.CustomersID, Orders.OrdersDate FRO

bottom of page