我有这个猫鼬模型
const reportUsSchema = new mongoose.Schema({
texts: [
{
text: { type: String, default: "" },
date_time: { type: Date, default: new Date() },
},
],
});
我想要这个:
每当在
texts
字段中推送新文本时,我想插入当前日期时间。
我得到什么(问题):
我得到的日期时间与上次重新启动服务器时的日期时间相同。例如,如果我在 2 天前重新启动了服务器,我会得到 2 天前的日期,这是错误的。
我尝试过的:
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() }
我目前在上面的代码中使用它,但以上都不适合我。
注意:有效的方法不是依赖猫鼬模型中的默认值,而是将当前日期时间值与文本一起传递。这运作良好。
我无法理解这种行为。帮助我理解我错在哪里。
猫鼬版本:5.10.7
编辑
我知道
new schema
的事情。我想知道我做错了什么,猫鼬的行为如此。我想了解这种行为。
模式中的default: new Date()选项意味着当创建文档或未指定该字段时,date_time字段将具有当前日期和时间的默认值。
您可以使用时间戳选项:
let ItemSchema = new Schema({
texts: [
{
text: { type: String, default: "" },
},
],
},
{
timestamps: true
});
您还可以指定时间戳字段:
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
根据您对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。