【问题标题】:Find by ISODate using Node.js, Express, and MongoDB使用 Node.js、Express 和 MongoDB 按 ISODate 查找
【发布时间】:2017-01-21 01:41:01
【问题描述】:

我在网络服务器上使用 Node.js 和 Express 来查询 dbserver 上的 MongoDB,并且遇到了让日期一起工作的问题,我在这里阅读了很多关于这个问题的线程,最值得注意的是这个:

Inserting and Querying Date with MongoDB and Nodejs

我很确定我明白我应该做什么,但我尝试的任何方法似乎都不起作用。

在我的 .js 文件中,我有以下内容:

var todayStart = new Date();
todayStart.setSeconds(0);
todayStart.setHours(0);
todayStart.setMinutes(0);
todayStart.setMilliseconds(0);

var todayEnd = new Date(todayStart);
todayEnd.setHours(23);
todayEnd.setMinutes(59);
todayEnd.setSeconds(59);
todayEnd.setMilliseconds(999);

var query = {
    "date": {
        $gte: new Date(todayStart).toISOString(),
        $lte: new Date(todayEnd).toISOString()
    }
};

我的查询变量以我期望的格式输出到控制台:

{ date:
   { '$gte': '2016-09-13T00:00:00.000Z',
     '$lte': '2016-09-13T23:59:59.999Z' }
}

我尝试使用我的查询变量或日期变量本身,并且都返回 null 结果(无错误):

db.collection('test').findOne(query, function(err, result) {
db.collection('test').findOne({"date" : {$gte: new Date(todayStart).toISOString(),$lte: new Date(todayEnd).toISOString() }}, function(err, result) {

但是,如果我像这样插入我的日期,它会返回我的结果:

db.collection('test').findOne({"date" : {$gte: new Date("2016-09-13T00:00:00.000Z"),$lte: new Date("2016-09-13T23:59:59.999Z") }}, function(err, result) {

知道我在这里缺少什么吗?

【问题讨论】:

    标签: javascript node.js mongodb express


    【解决方案1】:

    你可以使用isodate

      var isodate = require('isodate');
    
    
    
    var query = {
    
    "date" : {
                    '$gte' : isodate(todayStart ),
                    '$lt' : isodate(todayEnd )
                }
    };
    

    【讨论】:

      【解决方案2】:

      无需将日期转换为 ISO 字符串格式,只需使用 JS 日期查询即可。有关原因的详细说明,请参阅documentation

      您的开始日期对象应将当前日期时间的小时数保持在 00:00:00.000(毫秒精度)并将今天日期的小时数设置为 23:59:59.999 到结束日期变量:

      var todayStart = new Date();
      todayStart.setHours(0,0,0,0);
      
      var todayEnd = new Date();
      todayEnd.setHours(23,59,59,999);
      
      var query = {
          "date": {
              $gte: todayStart,
              $lte: todayEnd
          }
      };
      
      db.collection('test').findOne(query, function(err, result) {
          if (err) throw new Error();
          console.log(JSON.stringify(result));
      });
      

      如果您使用 momentjs 库,这可以通过使用 startOf()endOf() 方法来完成时刻的当前日期对象,将字符串“day”作为参数传递:

      var todayStart = moment().startOf('day'); // set to 12:00 am today
      var todayEnd = moment().endOf('day'); // set to 23:59 pm today
      

      【讨论】:

      • 非常感谢。我显然把它复杂化了。像魅力一样工作。
      • @NickSchroeder 不用担心,很乐意为您提供帮助
      猜你喜欢
      • 2013-08-01
      • 2014-03-20
      • 2021-08-27
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 2013-05-14
      相关资源
      最近更新 更多