温馨提示:本文翻译自stackoverflow.com,查看原文请点击:node.js - Mongoose: sort date doesn't work as date but text on my mongodb query
mongodb mongoose node.js

node.js - Mongoose :排序日期不能作为日期,但我的mongodb查询中的文本

发布于 2020-03-28 23:19:42

我的日期排序不能用作日期类型,但在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 ,它不应该检查格式吗?

查看更多

查看更多

提问者
adrien F
被浏览
121
adrien F 2020-02-07 19:42

我知道了 !

一切都很好,但是...我在排序日期中有一些空值。

这是按我的工作日期而定的所有可能的日期(取决于您的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) { ... });