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

TIMEX picture TIMEX · Apr 28, 2011 · Viewed 172.1k times · Source

let's say I run this query in Mongoose:

    Room.find({}, (err,docs) => {
    
    }).sort({date:-1}); 

This doesn't work!

Answer

JohnnyHK picture JohnnyHK · Feb 26, 2013

[Sorting][1] 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((err, docs) => { ... });
Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });

For an ascending sort, omit the - prefix on the string version or use values of 1, asc, or ascending. [1]: http://mongoosejs.com/docs/api.html#query_Query-sort