I am running into an interesting issue. I initially started diving into it here:
https://github.com/andrewplummer/Sugar/issues/78
But found out the vanilla JS produces the same issue. Whenever I store a date (no timestamp) and then I go to retrieve that date and format it, its a day behind. There is a simple example in the case, I can get you more info if you need. I'm central time. Here is a snippet of a stored doc in MongoDB that will be a date behind when I format it (e.g. getDate()).
{ "_id" : ObjectId("4eeb6c1822501a661600003b"),
"dateExample" : ISODate("2011-12-19T00:00:00Z")
}
Does mongoose store UTC dates to MongoDB or is there some other reason why this would be?
this happens independently of mongodb or mongoose. adjusting for your timezone will correct it. we use node-time for all our dates.
Thanks for your response, I'm unsure how to do this, are you referring to a system level adjustment or within the node code itself? Do you have an example?
we store the users timezone and use the date helper methods provided by node-time to adjust them accordingly. something like
var time = require('time')(Date);
User.findById(id, function (err, user) {
var date = new Date;
date.setTimezone(user.timezone)
// use the date
})
Thanks, that's super helpful!
@aheckmann how do you recommend storing dates (no timestamp) in mongo? (i.e. timezone shouldn't matter)?
ahh i think i got it, I can just format it as a UTC date when I want the "date" part to match what's in the database
i have a field like this....
"addedOn" : ISODate("2016-03-10T14:18:55.339Z")
and i wanna get count of data which are inserted today. how to get that????
Use $gte : moment.utc().startOf('day').toDate() and $lte: moment.utc().endOf('day').toDate()
how do i can store data with and without time??? like one field with datetime and another field only with date.
No way to do that right now. In the past I've just stored dates as a string in 'YYYYMMDD' format (like '20160317'). This has the nice feature that you can still sort by date and use ordering operators like $gt.
I need help to fetch data from mongodb using mongoose. I have to weekly data in graph. So If today is monday means i need data from last monday to this monday(today) and if today is tuesday means i need to show data from last tuesday to this tuesday(today). Help me pls.
@nasr18 MyModel.find({ timestamp: { $gte: moment().subtract(7, 'days').toDate(), $lte: moment().toDate() } });
Or use https://www.npmjs.com/package/mongodb-moment to make the toDate()
call unnecessary
Use $gte : moment.utc().startOf('day').toDate() and $lte: moment.utc().endOf('day').toDate()
Thanks man this made my day.
Most helpful comment
No way to do that right now. In the past I've just stored dates as a string in 'YYYYMMDD' format (like '20160317'). This has the nice feature that you can still sort by date and use ordering operators like $gt.