Mongoose 模型将默认日期保存为服务器上次启动的日期

问题描述 投票:0回答:2

我有这个猫鼬模型

const reportUsSchema = new mongoose.Schema({
  texts: [
    {
      text: { type: String, default: "" },
      date_time: { type: Date, default: new Date() },
    },
  ],
});

我想要这个:

每当在

texts
字段中推送新文本时,我想插入当前日期时间。

我得到什么(问题):

我得到的日期时间与上次重新启动服务器时的日期时间相同。例如,如果我在 2 天前重新启动了服务器,我会得到 2 天前的日期,这是错误的。

我尝试过的:

  1. 使用 moment.js:我也尝试了 moment.js 的多种组合。在这里添加它们:
date_time: { type: Date, default: moment() }

还有

date_time: { type: Date, default: moment().format() }

还有

date_time: { type: Date, default: moment().utc(true) }

还有

date_time: { type: Date, default: moment().utc(true).format() }
  1. 使用内置 Date()

我目前在上面的代码中使用它,但以上都不适合我。

注意:有效的方法不是依赖猫鼬模型中的默认值,而是将当前日期时间值与文本一起传递。这运作良好。

我无法理解这种行为。帮助我理解我错在哪里。

猫鼬版本:5.10.7

编辑

我知道

new schema
的事情。我想知道我做错了什么,猫鼬的行为如此。我想了解这种行为。

node.js mongodb datetime mongoose momentjs
2个回答
1
投票

模式中的default: new Date()选项意味着当创建文档或未指定该字段时,date_time字段将具有当前日期和时间的默认值。

您可以使用时间戳选项:

let ItemSchema = new Schema({
  texts: [
    {
      text: { type: String, default: "" },
    },
  ],
},
{
  timestamps: true
});

您还可以指定时间戳字段:

timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }

0
投票

根据您对this答案的评论,您需要更新您的架构以使用

Date.now
而不是
new Date()
,如下所示:

const reportUsSchema = new mongoose.Schema({
  texts: [
    {
      text: { type: String, default: "" },
      date_time: { type: Date, default: Date.now }, //< This change
    },
  ],
});

这是因为当您使用

default: new Date()
时,您是在告诉架构使用默认日期 在定义架构时,而不是文档。因此,如果您将应用程序部署到服务器,然后启动应用程序,则该架构中该字段的默认值将是您的应用程序启动的时间。

但是,如果您使用

Date.now
,那么 mongoose 知道在创建文档时设置默认值以使用日期时间

在 mongoose

docs 中,他们确实推荐了这个:updated: { type: Date, default: Date.now },

 在他们的厨房水槽示例中。他们还在默认函数示例中列出了
here

© www.soinside.com 2019 - 2024. All rights reserved.