Clients can show 'showing 1-20 of 432' and decide whether to show a next button. Use Promise.all([find, countDocuments]) to run both queries in parallel and avoid waterfall delays.
API Pagination, Filtering, and Sorting in Express
Why return total in paginated responses?
The answer
More FAQs in API Pagination, Filtering, and Sorting in Express
Use skip and limit: User.find().skip(parseInt(req.query.skip) || 0).limit(Math.min(parseInt(req.query.limit) || 20, 100)). Always cap limit (e.g., max 100) to prevent abuse.
Instead of skip (which scans skipped docs), use a cursor like the last createdAt. Find documents where createdAt is less than the cursor. Faster for very large collections because MongoDB uses an index.
Build a filter object from query params. if (req.query.role) filter.role = req.query.role. Pass the filter to User.find(filter). Whitelist allowed filters to prevent arbitrary queries.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.