In Mongoose, sorting can be achieved by using the .sort() method after your query. This method accepts a parameter that can be a string or an object, specifying the fields to sort by and the sort order (ascending or descending). In MongoDB, ascending order is denoted by 1, and descending order by -1.
Sorting Using Strings
If you need to sort by a single field, you can directly pass the field name with a - prefix for descending order, or without any prefix for ascending order.
javascript// Ascending sort MyModel.find().sort('field').exec((err, docs) => { // Handle results or errors }); // Descending sort MyModel.find().sort('-field').exec((err, docs) => { // Handle results or errors });
Sorting Using Objects
If you need to sort by multiple fields, you can pass an object where the keys are field names and the values are 1 or -1 to represent ascending or descending order respectively.
javascript// Sorting by multiple fields MyModel.find().sort({ field1: 1, field2: -1 }).exec((err, docs) => { // Handle results or errors });
Example
Suppose you have a user model User, and you want to sort by age in ascending order and then by username in descending order; you can do the following:
javascriptUser.find().sort({ age: 1, username: -1 }).exec((err, users) => { if (err) { console.error(err); } else { console.log(users); // This outputs an array of users sorted by age ascending and username descending } });
This approach allows you to easily sort query results by one or multiple fields, which is particularly useful when handling large datasets to quickly locate relevant records.