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.
API Pagination, Filtering, and Sorting in Express
How do I filter an Express API?
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.
Use sortBy and order query params. const sortBy = req.query.sortBy || 'createdAt'; const order = req.query.order === 'asc' ? 1 : -1. User.find().sort({ [sortBy]: order }). Whitelist sortable fields.
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.