简体   繁体   中英

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.

var time = new Date(2013,11,31,3,0,0,0);

This Date prints out as follows using 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. The Mongo shell shows the document exists. 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". But the version of new Date that you're using:

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:

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.

Probably the easiest thing to do is to use Date.UTC to convert your components to UTC before creating your Date instance:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM