How do I sort an Express API?
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.
Verify This Answer
Cross-check this information using these trusted sources:
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
