Mongoose saving and retrieving dates with UTC time

2019-05-31 10:03发布

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?

1条回答
爷的心禁止访问
2楼-- · 2019-05-31 10:34

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?

If by "today's midnight" you mean the last midnight that happened (in which case you will not get results from a moment ago), then you can use something like this - using your local time zone:

// use moment-timezone to handle time zones correctly:
const moment = require('moment-timezone');

let end = moment().startOf('day').tz('UTC')
let start = end.subtract(10, 'days');

or explicitly using Asia/Calcutta time zone:

let end = moment.tz('Asia/Calcutta').startOf('day').tz('UTC');
let start = end.subtract(10, 'days');

If by "today's midnight" you mean the next midnight that will happen (in which case you will get results from a moment ago), then you can use something like this - using your local time zone:

let end = moment().endOf('day').tz('UTC')
let start = end.subtract(10, 'days');

or explicitly using Asia/Calcutta time zone:

let end = moment.tz('Asia/Calcutta').endOf('day').tz('UTC');
let start = end.subtract(10, 'days');

You will have UTC dates that correspond to your local midnights, ready to use in Mongo queries.

No need to change anything in Mongo.

查看更多
登录 后发表回答