[node.js] 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!

This question is related to node.js mongodb mongoose

The answer is


The correct answer is:

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

});

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.



ES6 solution with Koa.

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

I do this:

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

This will show the most recent things first.


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.


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
});

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});
 });`

Short solution:

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

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

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?

Examples related to mongoose

Querying date field in MongoDB with Mongoose Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Mongodb: failed to connect to server on first connect Push items into mongo array via mongoose Mongoose: findOneAndUpdate doesn't return updated document mongoError: Topology was destroyed Difference between MongoDB and Mongoose How can you remove all documents from a collection with Mongoose? E11000 duplicate key error index in mongodb mongoose