How to sort in mongoose?

826    Asked by VirginiaMathis in Devops , Asked on Jul 18, 2021
 I find no doc for the sort modifier. The only insight is in the unit tests: spec.lib.query.js#L12
writer.limit(5).sort(['test', 1]).group('name')

But it doesn't work for me:

Post.find().sort(['updatedAt', 1]);

Dont know mongoose sort?

Answered by Oliver Thomas

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

 You can use the below-mentioned code to sort in MongoDB :-

News.find({ 
deal_id:deal._id
},
['type','date_added'],
{
skip:0,
limit:10,
sort:{
date_added: -1
}
},
function(err,allNews){
socket.emit('news-load', allNews);
})

Your Answer

Interviews

Parent Categories