Mongodb时间戳非常不准确-猫鼬 [英] Mongodb timestamp is very inaccurate - mongoose

查看:508
本文介绍了Mongodb时间戳非常不准确-猫鼬的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用猫鼬在mongodb中存储对象,我通过使用Date.now()记录了createdAt日期

I am using mongoose to store objects in mongodb, I record the createdAt date by using Date.now()

我发现的是数据库中存储的时间错误.差异非常零星,已经有7天,3天甚至5分钟了.

What I am finding is that the wrong time is being stored in the database. The difference is very sporadic and has been 7 days, 3 days and even 5 minutes off.

今天早上,我在美国东部标准时间8:00 AM(GMT + 10)创建了一个对象,但是数据库中的时间早了7天.

Just this morning I created an object at 8.00AM (GMT+10) AEST, yet the time in the database was 7 days earlier.

这是数据库对象:

{
  "_id": "554bdfaf797cb8e02753e06f",
  "description": "test d",
  "createdBy": "testuser",
  "key": "f1a593f4dd51e632388a1755e09a7b4dc0bc0e24ef8bcf5cf859ac759a45e8a6",
  "__v": 0,
  "files": [],
  "createdAt": "2015-05-01T05:42:07.687Z"
}

我在Mac和Win 7上都看到了这个问题.

I have seen this issue on both on my mac and win 7.

首先在mongodb 2.6.3版上注意到,刚刚升级到3.0.2,没有变化.

First noticed on mongodb version 2.6.3, just upgraded to 3.0.2, no change.

更新

我正在如下模式中设置createdAt日期:

I am setting the createdAt date within the schema like so:

var uploadSchema = new Schema({
    createdAt: {
        type: Date,
        required: true,
        default: Date.now()
     },

我的数据库和应用程序在同一主机上运行.

My database and application are running on the same host.

要点在这里- https://gist.github.com/reecefenwick/1bcff85d18406b33e5cf

推荐答案

正在发生的情况是,您在定义架构以设置createdAt,然后将该值用作默认值,直到下次重新启动您的应用为止.

What's going on is that you're calling Date.now() at the time the schema is defined to set the default value for createdAt, and then that value is being used for the default until the next time your app is restarted.

相反,您想将默认值设置为Date.now函数本身,以便在每次创建新文档时都将调用它:

Instead, you want to set the default value to the Date.now function itself so that it will be called each time a new doc is created:

var uploadSchema = new Schema({
    createdAt: {
        type: Date,
        required: true,
        default: Date.now
     },

这篇关于Mongodb时间戳非常不准确-猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆