Monday, 24 April 2017

Mongoose saving and retrieving dates with UTC time, change to server timezone

I'm using mongoose models to save my records including created and updated dates. Here's my model schema:

var CasesModelSchema = new mongoose.Schema(
    {
        caseId: Number,
        sessionId: String,
        createdAt: {type: Date},
        updatedAt: {type: Date, default: Date.now},
        docs: mongoose.Schema.Types.Mixed
    },
    {
        collection: 'cases'
    }
);

The problem I'm facing is that the updatedAt field saves the datetime as ISODate("2017-04-24T12:40:48.193Z"), which is in UTC, but my server's timezone is Asia/Calcutta. Since I need to make queries according to my server's time, I need the datetimes to be saved in my preferred timezone.

Here's the query I need to execute (get all data for the last 10 days)

var today = moment(moment().format('YYYY-MM-DD')).toDate();
var tenDaysDate = moment(moment().format('YYYY-MM-DD')).add(-10, 'days').toDate();

CasesModel.findOne({updatedAt: {$gte: tenDaysDate, $lt: today}}, 
    function(err, caseData){
    cl(caseData, __line);
});

What I want is to do a query to get all the updated records in the last 10 days, exactly from 10 days ago midnight (Asia/Calcutta timezone) to today's midnight (Asia/Calcutta timezone). How do I do that?



via gaganshera

No comments:

Post a Comment