0

This has probably been asked a hundred times, yet I dare to ask: In express / mongoose I need to create a UTC ISO date in order to query MongoDB. This is what I am doing:

var date = new Date(req.params.date + " 00:00:00 UTC").toUTCString();

Whereas req.params.date equals this string: 2015-01-01.

Above line creates: Mon, 12 Jan 2015 00:00:00 GMT, in MongoDB I have:

"date" : ISODate("2014-12-08T00:00:00.000Z")

How do I get this to work?

Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147

3 Answers3

2

You need to represent the date in your query as a standard JavaScript Date object.

So leave off the toUTCString() part and something like this will work:

var date = new Date(req.params.date);
collection.findOne({date: date}, callback);

The ISODate stuff confuses so many people (myself included for the longest time). ISODate is just a MongoDB shell construct, date objects are stored as 64-bit integer BSON Date objects in MongoDB.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
0

Instead of toUTCString() I used the toISOString() method of the Date object, this worked fine.

var date = new Date(req.params.date + " 00:00:00 UTC").toISOString();

Also see. Inserting and Querying Date with MongoDB and Nodejs

Community
  • 1
  • 1
Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147
0

Convert UTC string to Date Object

    var utc_date=new Date(new Date().toUTCString());