【问题标题】:comparing dates to retrieve data比较日期以检索数据
【发布时间】:2012-01-13 22:33:57
【问题描述】:

我在 mongodb 中有类似的数据

{ "_id" : ObjectId("4f0ee7310b09f7a254000001"), "createdAt" : ISODate("2012-01-12T23:58:28Z") }
{ "_id" : ObjectId("4f0ee7350b09f7a254000002"), "createdAt" : ISODate("2012-01-12T23:58:28Z") }
{ "_id" : ObjectId("4f0ee855e63cecb654000001"), "createdAt" : ISODate("2012-01-13T00:03:59Z") }
{ "_id" : ObjectId("4f0ee859e63cecb654000002"), "createdAt" : ISODate("2012-01-13T00:04:08Z") }
{ "_id" : ObjectId("4f0ee97c212d70bc54000001"), "createdAt" : ISODate("2012-01-13T00:08:54Z") }
{ "_id" : ObjectId("4f0ee99f212d70bc54000002"), "createdAt" : ISODate("2012-01-13T00:09:27Z") }

我只想显示基于日期的记录。检查我的代码它什么也没给我

//dateStr = '120112' or '120113'
var year = '20' + dateStr.substring(0,2);
var month =  dateStr.substring(2,4);
var day =  dateStr.substring(4);
dateStr = new Date(year,month,day,0,0,0);

var nextDate = new Date(year,month,day,23,59,59);

GPSData.find({"createdAt" : { $gte : dateStr, $lte:  nextDate }}, function(err, data) {
    if(err)
        console.log(err); 

    res.writeHead(200, {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*"
    });
    var body = JSON.stringify(data);
    res.end(body);  //no output here just []
});

但在使用此命令的 mongo shell 上,我得到日期“120112”的结果

db.gpsdatas.find({"createdAt" : {new ISODate("2012-01-12T00:00:00Z"), $lte: new ISODate("2012-01-12T23:59:59Z") }});

【问题讨论】:

  • 不知道 mongoose 是如何工作的,但你可以试试 {"createdAt" : { $gte : dateStr}, "createdAt" : { $lte: nextDate }}

标签: node.js mongodb mongoose


【解决方案1】:

您的问题是您对 Date 类的理解。我假设您正在尝试为 1 月 12 日创建一个日期对象,但 new Date(2012, 1, 12) 实际上是 2 月 11 日或 12 日,具体取决于当地时区。因此,您的代码不会执行您在 shell 中执行的查询。

在此处阅读详细信息http://www.w3schools.com/jsref/jsref_obj_date.asp

【讨论】:

    【解决方案2】:

    未经我自己测试的盲目回答:如果将此行添加到 GPSData.find(..) 行之前会发生什么?

    dateStr = dateStr.toString();
    nextDate = nextDate.toString();
    

    另外,请尝试使用 console.log 来查看输出字符串的外观。它的格式可能与您预期的完全不同。

    【讨论】:

    • 我的意思是:如果你做一个字符串比较会发生什么?
    猜你喜欢
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    相关资源
    最近更新 更多