Use sortBy and order query params. Whitelist sortable fields to prevent errors and abuse. const sortBy = allowedSorts.includes(req.query.sortBy) ? req.query.sortBy : 'createdAt'. Use .sort({ [sortBy]: order }).
Filtering and Sorting in Node.js APIs: A Complete Guide
How do I implement sorting in a Node.js API?
The answer
More FAQs in Filtering and Sorting in Node.js APIs: A Complete Guide
Use query params. Build a filter object based on which params are present. Whitelist the fields users can filter by to prevent query injection. Pass the filter to Model.find(filter).
To prevent query injection (users setting arbitrary filter fields to probe your data) and errors (users sorting by a field that does not exist). Whitelisting limits the surface and keeps the API predictable.
Build a filter, sort, and select from query params. Then User.find(filter).sort(sort).skip(skip).limit(limit).select(select).lean(). Run find and countDocuments in parallel with Promise.all. Return { data, total, skip, limit }.
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.