So the client 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.
How to Build a Feed API in Node.js
Why return total in a paginated feed?
The answer
More FAQs in How to Build a Feed API in Node.js
GET /feed?skip=&limit=. Exclude the current user and already-swiped users. Cap the limit. Use .lean() and .select(). Return total. Run find and countDocuments in parallel with Promise.all. Index the filter fields.
Fetch the swiped user IDs with ConnectionRequest.find({ fromUserId }).distinct('toUserId'). Then filter the feed with _id: { $nin: [req.user.userId, ...swipedIds] }. Excludes the current user and anyone already swiped on.
To prevent abuse. Without a cap, a client can request 10000 items, eating memory and bandwidth. Use Math.min(parseInt(req.query.limit) || 20, 100). Most UIs only show 20 at a time anyway.
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.