In Mongoose, how do I sort by date? (node.js)
let's say I run this query in Mongoose:
Room.find({}, (err,docs) => {
}).sort({date:-1});
This doesn't work!
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((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
.
The correct answer is:
Blah.find({}).sort({date: -1}).execFind(function(err,docs){
});
Been dealing with this issue today using Mongoose 3.5(.2) and none of the answers quite helped me solve this issue. The following code snippet does the trick
Post.find().sort('-posted').find(function (err, posts) {
// user posts array
});
You can send any standard parameters you need to find()
(e.g. where clauses and return fields) but no callback. Without a callback it returns a Query object which you chain sort()
on. You need to call find()
again (with or without more parameters -- shouldn't need any for efficiency reasons) which will allow you to get the result set in your callback.