I am trying to query MongoDb using a date range in my FindOne
statement, but I cannot get it to work. I am using the Nodejs native driver. I've tried various options, but nothing is returning the expected record.
Here is my pseudo-code -
console.log(sDate); // displays Fri Jun 20 2014 10:00:00 GMT+1000 (AUS Eastern Standard Time)
var sDateISO = sDate.toISOString();
console.log(sDateISO); // displays 2014-06-20T00:00:00.000Z
// all of these return null object
db.collection('events').findOne(
{ eventStartDate: { $lte: new Date(sDate)}},
function(err, obj) { console.dir(obj); } // displays null
);
db.collection('events').findOne(
{ eventStartDate: { $lte: (sDate) }},
function(err, obj) { console.dir(obj); } // displays null
);
db.collection('events').findOne(
{ eventStartDate: { $lte: new Date(sDateISO) }},
function(err, obj) { console.dir(obj); } // displays null
);
db.collection('events').findOne(
{ eventStartDate: { $lte: (sDateISO) }},
function(err, obj) { console.dir(obj); } // displays null
);
However, if I run this in RoboMongo, the record is returned as expected -
==========
UPDATE
My problem was elsewhere in my code -- I had a type mismatch problem in a separate parameter passed to the FindOne
query.
As stated in the documentation, and confirmed by Christian P below, I can use my Javascript date object sDate
in the FindOne
query directly.
I used a typeOf
function (found here) to confirm sDate
is indeed a Date object.
So, after inspecting all other variables in my actual code, I found the problem elsewhere, unrelated to the Date object / parameter.