[英]Searching by Time - MongoDB / NodeJS
I have a document with the following time: 我有以下时间的文档:
"time" : ISODate("2013-12-31T03:00:00Z")
I'm currently trying to find this document using a MongoDB query with the Node.JS driver. 我目前正在尝试使用带有Node.JS驱动程序的MongoDB查询来查找此文档。
var time = new Date(2013,11,31,3,0,0,0);
This Date prints out as follows using console.log() 该日期使用console.log()打印如下
Tue Dec 31 2013 03:00:00 GMT-0500 (EST)
When I try to find this document using the standard collection.findOne (I'm positive the query itself isn't the problem, rather the timestamp), it doesn't find the document. 当我尝试使用标准collection.findOne查找该文档时(我很肯定查询本身不是问题,而是时间戳),它找不到该文档。 The Mongo shell shows the document exists.
Mongo Shell显示该文档存在。 How have I formatted my time incorrectly?
我如何格式化时间错误?
EDIT: I'll add in the query too. 编辑:我也会在查询中添加。
collection.findOne(
{
"time" : time},
{"_id" : 0},
function(err, items){
if (err){
throw err;
}
console.log(err);
console.log(items);
res.send(items);
});
You have a time zone problem. 您有时区问题。 The timestamp you're looking for is
2013-12-31T03:00:00Z
, the trailing Z
means "zero time zone offset". 您要查找的时间戳是
2013-12-31T03:00:00Z
,后缀Z
表示“零时区偏移”。 But the version of new Date
that you're using: 但是您正在使用的
new Date
的版本:
var time = new Date(2013,11,31,3,0,0,0);
interprets all those values in the current time zone. 解释当前时区中的所有这些值。 If we look at your
console.log
output: 如果我们查看您的
console.log
输出:
Tue Dec 31 2013 03:00:00 GMT-0500 (EST)
we can see that you're in the EST time zone and that your time
is 03:00
in EST rather that 03:00
in UTC. 我们可以看到您处于EST时区,您的
time
在EST是03:00
,而在UTC是03:00
。
Probably the easiest thing to do is to use Date.UTC
to convert your components to UTC before creating your Date
instance: 可能最简单的方法是在创建
Date
实例之前使用Date.UTC
将组件转换为UTC:
var time = new Date(Date.UTC(2013,11,31,3,0,0,0));
Now you should have 2013-12-31T03:00:00Z
in your time
and your query should work better. 现在您应该有
2013-12-31T03:00:00Z
的time
,查询应该会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.