Categories
JavaScript Answers

How to sort in Node.js Mongoose?

Spread the love

Sometimes, we want to sort in Node.js Mongoose.

In this article, we’ll look at how to sort in Node.js Mongoose.

How to sort in Node.js Mongoose?

To sort in Node.js Mongoose, we can use the sort method.

For instance, write:

Post.find({}).sort('test').exec((err, docs) => {
  //...
});

to call sort with the property to sort by.

We can sort descending with

Post.find({}).sort([
  ['date', -1]
]).exec((err, docs) => {
  //...
});

We call sort with a nested array with the property name and -1.

The exec callback is run when the sorting is done.

docs has the sorted data.

Conclusion

To sort in Node.js Mongoose, we can use the sort method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *