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

node.jsMongodbMongoose

node.js Problem Overview


let's say I run this query in Mongoose:

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

This doesn't work!

node.js Solutions


Solution 1 - node.js

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.

Solution 2 - node.js

The correct answer is:

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

});

Solution 3 - node.js

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.

Solution 4 - node.js

Post.find().sort({date:-1}, function(err, posts){
});

Should work as well

EDIT:

You can also try using this if you get the error sort() only takes 1 Argument :

Post.find({}, {
	'_id': 0,    // select keys to return here
}, {sort: '-date'}, function(err, posts) {
	// use it here
});

Solution 5 - node.js

I do this:

Data.find( { $query: { user: req.user }, $orderby: { dateAdded: -1 } } function ( results ) {
	...
})

This will show the most recent things first.

Solution 6 - node.js

Solution 7 - node.js

Short solution:

const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }

Room.find(query, projection, options).exec(function(err, docs) { ... });

Solution 8 - node.js

All the anwsers here are factually correct, however I am writing my anwser to make it clear that sometimes writing '-date' or date: -1 won't work if you either don't have a field named 'date' in your model, or if you passed the option: timestamps: true in options when creating your model. If you are using timestamps: true then you need to type: sort({createdAt: -1}) and this will work then.

Solution 9 - node.js

This one works for me.

`Post.find().sort({postedon: -1}).find(function (err, sortedposts){
    if (err) 
        return res.status(500).send({ message: "No Posts." });
    res.status(200).send({sortedposts : sortedposts});
 });`

Solution 10 - node.js

ES6 solution with Koa.

  async recent() {
    data = await ReadSchema.find({}, { sort: 'created_at' });
    ctx.body = data;
  }

Solution 11 - node.js

You can also sort by the _id field. For example, to get the most recent record, you can do,

const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });

It's much quicker too, because I'm more than willing to bet that your date field is not indexed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - node.jsJohnnyHKView Answer on Stackoverflow
Solution 2 - node.jsTIMEXView Answer on Stackoverflow
Solution 3 - node.jsJimmy HillisView Answer on Stackoverflow
Solution 4 - node.jslynx_vbgView Answer on Stackoverflow
Solution 5 - node.jsNoahView Answer on Stackoverflow
Solution 6 - node.jsneebzView Answer on Stackoverflow
Solution 7 - node.jsdavidsonsnsView Answer on Stackoverflow
Solution 8 - node.jsms3300View Answer on Stackoverflow
Solution 9 - node.jsUsama TahirView Answer on Stackoverflow
Solution 10 - node.jschovyView Answer on Stackoverflow
Solution 11 - node.jsMike KView Answer on Stackoverflow