Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by date and time in mongoose?

Can someone tell me how I can sort an array of items according to date and time. Currently, I am using

image.find({reviewed:true }, null, {sort:{"submittedDate":-1}}, 
           function (err, images) {})

My schema for date is:

submittedDate: Thu, 08 Nov 2012 15:42:47 GMT

But it sort only date wise. I want to sort first by time then by date.

Any help will be appreciated.

like image 245
Ali Hassan Avatar asked Nov 08 '12 16:11

Ali Hassan


2 Answers

As per version 5.11.13.

  1. Add { timestamps: true } in your Schema.

    new Schema({}, { timestamps: true });

  2. Then Add "sort" to your query.

    Model.find({}).sort({ createdAt: 'desc'}).exec();

    Model.find({}).sort({ createdAt: 'asc'}).exec();

Thanks.

like image 63
Sushil Avatar answered Sep 22 '22 02:09

Sushil


The way to sort would be:

image.find({reviewed:true})
     .sort({'submittedDate': 'desc'})
     .exec(function(err, images) {
         //do stuff with images
     });

Some documentation.

From v3.8.1, the syntax would be:

image.find({reviewed:true})
     .sort('submittedDate', -1)
     .execFind(function(err, images) {

 });
like image 33
Alex Avatar answered Sep 24 '22 02:09

Alex