Mongoose或MongoDB从24小时开始删除?

时间:2018-03-26 13:12:40

标签: mongodb date mongoose

我必须做错事但我无法弄清楚它是什么。我目前在我的应用程序中有一个日期字段,其值格式为MMMM,D YYYY。

对于这个例子,我将使用2018年10月1日的日期。

在应用程序中,用户选择2018年10月1日记录为

October 1, 2018

稍后我使用var docDate = new Date($('#insuranceExpiration').val()).toISOString();将日期转换为可保存的日期,并将其记录为

2018-10-01T04:00:00.000Z

然后我将它添加到一个对象stringify它并将其发送到我记录日期的服务器并显示为

2018-10-01T04:00:00.000Z

然后我使用Mongoose将此日期保存到MongoDB,但是当我去看看我显示的保存日期时

2018-09-30T04:00:00.000Z

我无法弄清楚为什么我从我选择之日起24小时内看到约会的原因。下面是猫鼬代码,看看我是否在这方面做错了什么。

app.post('/api/myDocuments/insuranceGeneral', function(req, res ) {

    console.log(req.body.expires);
    // prints 2018-10-01T04:00:00.000Z

    InsuranceGeneral.findOneAndUpdate({
        _id: req.rsaConPortal.id
    }, {
        $set: {
            "documents.insurance.name": req.body.name,
            "documents.insurance.expires": req.body.expires,
            "documents.insurance.url": req.body.url,
            "documents.insurance.uploadDate": req.body.uploadDate
        }
    }, function(err, doc) {

       if (err) throw err;

        res.send('Success');

    });

});

即使我使用标准的javascript日期对象,我也可以在浏览日志

上打印

Mon Oct 01 2018 00:00:00 GMT-0400 (Eastern Daylight Time)

这会在mongoose之前在服务器上打印

2018-10-01T04:00:00.000Z

但这是mongodb的最终结果

2018-09-30T04:00:00.000Z

1 个答案:

答案 0 :(得分:0)

我认为您和您的服务器处于不同的时区。 mongodb使用GMT。如果您没有在iso日期宣布时间,则将其设置为00:00.000Z。所以对于GMT来说,这是前一天。您只需将日期转换为GMT,就可以使用moment,或者您可以通过减法偏移来修复问题,如下所示:

var offset = new Date().getTimezoneOffset() * 60000;


var date = new Date(new Date($('#insuranceExpiration').val())) - offset).toISOString();

或使用moment.js

var date = moment($('#insuranceExpiration').val()).tz('GMT').format('YYYY-MM-DD');