In Mongoose, how do I sort by date? (node.js)


Question

let's say I run this query in Mongoose:

Room.find({}, function(err,docs){

}).sort({date:-1}); 

This doesn't work!

1
136
4/28/2011 9:55:20 PM

Accepted Answer

Sorting in Mongoose has evolved over the releases such that some of these answers are no longer valid. As of the 4.1.x release of Mongoose, a descending sort on the date field can be done in any of the following ways:

Room.find({}).sort('-date').exec(function(err, docs) { ... });
Room.find({}).sort({date: -1}).exec(function(err, docs) { ... });
Room.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
Room.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
Room.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Room.find({}, null, {sort: '-date'}, function(err, docs) { ... });
Room.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });

For an ascending sort, omit the - prefix on the string version or use values of 1, asc, or ascending.

378
8/22/2015 9:08:45 PM

The correct answer is:

Blah.find({}).sort({date: -1}).execFind(function(err,docs){

});

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon