Javascript Mongoose 日期字段 - 设置默认为 date.now + N 天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29899208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose date field - Set default to date.now + N days
提问by HdN8
In a mongoose schema such as:
在猫鼬模式中,例如:
var EventSchema = new Schema({
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
description: {
type: String,
default: '',
trim: true
},
start: {
type: Date,
default: Date.now,
required: 'Must have start date - default value is the created date'
},
end: {
type: Date,
default: Date.now + 7 Days, // Date in one week from now
required: 'Must have end date - default value is the created date + 1 week'
},
tasks: [{
type: Schema.ObjectId,
ref: 'Task'
}]
});
On the line for the "end" field the default date should set to +7 days. I can add presave hook and set it there, but wondering if theres a way to do this inline in the default field.
在“结束”字段的行上,默认日期应设置为 +7 天。我可以添加 presave 钩子并将其设置在那里,但想知道是否有办法在默认字段中内联执行此操作。
采纳答案by Viktor Kireev
You can add 7 days converted to milliseconds to current date like this
您可以像这样将转换为毫秒的 7 天添加到当前日期
default: new Date(+new Date() + 7*24*60*60*1000)
or even like this
甚至像这样
default: +new Date() + 7*24*60*60*1000
UPDATE
更新
Please check the @laggingreflex comment below. You need to set function as default value:
请查看下面的@laggingreflex 评论。您需要将函数设置为默认值:
default: () => new Date(+new Date() + 7*24*60*60*1000)
回答by Akhmedzianov Danilian
default: () => Date.now() + 7*24*60*60*1000
This will be enough
这将足够

