Reputation: 3953
I am trying to return search results for every document that was created on a day. Below is the query I use.
var query = Document.find({}).populate('contacts');
var gte = moment(req.query.date, 'DD-MM-YYYY').startOf('Day');
var lte = moment(req.query.date, 'DD-MM-YYYY').endOf('Day');
query.where('dates.createdAt').gte(gte).lt(lte);
This query works for some days but not all. I can't seem to understand the behaviour. Please help out.
The format of the date in the query string is DD/MM/YYYY
.
Works for : 2016-04-16T00:02:30.065Z
Does not work for: 2016-04-15T19:02:59.758Z
Upvotes: 2
Views: 862
Reputation: 50426
It's wrong because you don't initialize as .utc()
, and MongoDB dates are stored in UTC:
var gte = moment.utc(req.query.date, 'DD-MM-YYYY');
var lte = moment.utc(req.query.date, 'DD-MM-YYYY').endOf('Day');
And there is no need for the startOf()
either.
If you don't construct like that, then the resulting Date
object is skewed by the difference in the local timezone. Hence why you don't see the selection working where the hours would cross over dates.
Also if dates are coming in as 01/01/2016
then the format string would be 'DD/MM/YYYY'
, but one or the other is likely a typo in your question.
Upvotes: 2