My sort on date doesn't work as date type but text type on my mongodb query.
I have a document "affaire" looking like this :
{
"_id": {
"$oid": "5e32b42467e488e064972adf"
},
"Adresse": "22 rue des rosiers 75005 PARIS",
"Date_de_prochaine_echeance": {
"$date": {
"$numberLong": "1461715200000"
}
},
...
}
the mongoose declaration :
{
...
"Date_de_prochaine_echeance": { "type": "Date" },
...
}
My query looks like this
affaire.find().sort([['Date_de_prochaine_echeance', -1]]).
select("Adresse ").
exec(function (err, affaire) { ...});
My insert looks like this (I notice that not all my dates are insert the same way, I'm full of shame) :
new affaire({ ...
"Date_acceptation": req.body.Date_acceptation||new Date(),
"Date_de_prochaine_echeance": new moment(req.body.Date_de_prochaine_echeance||"2099-01-01T00:00:00.000Z").toDate(),
...
});
nb : I've used the moment.js lib
The sort function doesn't work as it was a date field but text field. I see on some answer that the format of the date may not be good. But I don't get how to correct all my dates with ISODate("2018-03-16T06:30:00Z").
The date seems to be a proper date format since the Compass interface interprete correctly the date.
I'm working with mongoose, shouldn't it check for format?
I got it !
Everything was right but ... I had some null values in the sorted dates.
This is all the possible sort by date that my work or not (depending of your version of mongodb) :
Room.find({}).sort('-date').exec(function(err, docs) { ... });
Room.find({}).sort({date: -1}).exec(function(err, docs) { ... });
Room.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
Room.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
Room.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Room.find({}, null, {sort: '-date'}, function(err, docs) { ... });
Room.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });