Explain Codes LogoExplain Codes Logo

How to sort in mongoose?

javascript
mongoose
sorting
pagination
Alex KataevbyAlex Kataev·Aug 9, 2024
TLDR

Sort data in Mongoose using .sort({ field: 1}) for ascending, and .sort({ field: -1 }) for descending order.

// Ascending: Taking the stairway to heavan YourModel.find().sort({ field: 1 }).exec(); // Descending: Going downhill YourModel.find().sort({ field: -1 }).exec();

Remember to chain .sort() after .find(). Need to sort on multiple fields? Just extend the object: .sort({ field1: 1, field2: -1 }).

Sort the Sortables

Hierarchical multi-field sort

Sorting on multiple fields is straightforward: simply set the priority by sequencing the fields in the sort object.

// From most significant to least. YourModel.find().sort({ primaryField: 1, secondaryField: -1 }).exec();

Case-insensitive string sorting

Sorting strings can be tricky. You will need to set a collation with your locale to sort case-insensitively:

YourModel.find().collation({ locale: 'en' }).sort({ stringField: 1 }).exec();

Paginated sorting

You can combine .sort() with .limit() and .skip() to implement pagination:

let pageSize = 10; let page = 2; // Paging through: one page at a time. YourModel.find() .sort({ field: 1 }) .skip(pageSize * (page - 1)) .limit(pageSize) .exec();

Pro-level Sorting Strategies and Pitfalls

Mandatory .exec() usage

Always remember to call .exec() to execute the query and return a promise. It makes your code cleaner and ready for using then.

YourModel.find().sort({ field: 1 }).exec().then(docs => { /* handle results like a boss */ });

Nested-field sorting

Dot notation unlocks sorting by nested fields:

YourModel.find().sort({ 'nested.field': 1 }).exec();

Error handling and precautions

ALWAYS handle errors to catch issues related to invalid fields or sorting logic:

YourModel.find().sort({ field: 1 }).exec((err, docs) => { if (err) { // Whoopsies! Gonna have to catch that one! } else { // Moving on, nothing to see here... } });

Performance-focused sorting

In large datasets, sorting on indexed fields yields better performance. Mongoose wisely uses same index for filtering and sorting the data.

Aggregation pipeline sorting

In aggregation pipelines, the $sort command sorts in style:

YourModel.aggregate([{ $sort : { field : 1 } }]);