我的日期排序不能用作日期类型,但在mongodb查询中为文本类型。
我有一个文件“ affaire”,看起来像这样:
{
"_id": {
"$oid": "5e32b42467e488e064972adf"
},
"Adresse": "22 rue des rosiers 75005 PARIS",
"Date_de_prochaine_echeance": {
"$date": {
"$numberLong": "1461715200000"
}
},
...
}
Mongoose 声明:
{
...
"Date_de_prochaine_echeance": { "type": "Date" },
...
}
我的查询看起来像这样
affaire.find().sort([['Date_de_prochaine_echeance', -1]]).
select("Adresse ").
exec(function (err, affaire) { ...});
我的插入看起来像这样(我注意到并不是所有的日期都以相同的方式插入,我感到很遗憾):
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:我用过moment.js库
排序功能不起作用,因为它是日期字段,但是文本字段。我在某些答案上看到日期的格式可能不好。但是我不知道如何使用ISODate(“ 2018-03-16T06:30:00Z”)更正所有日期。
由于Compass界面正确解释了日期,因此日期似乎是正确的日期格式。
我正在使用 Mongoose ,它不应该检查格式吗?
我知道了 !
一切都很好,但是...我在排序日期中有一些空值。
这是按我的工作日期而定的所有可能的日期(取决于您的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) { ... });