猫鼬日期字段 - 将默认设置为date.now + N天

时间:2015-04-27 14:59:04

标签: javascript mongoose

在mongoose模式中,例如:

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'
	}]
});

在“结束”字段的行上,默认日期应设置为+7天。我可以添加预设钩子并将其设置在那里,但想知道是否有一种方法可以在默认字段中内联。

2 个答案:

答案 0 :(得分:21)

default: () => Date.now() + 7*24*60*60*1000

这就够了

答案 1 :(得分:14)

您可以将转换为毫秒的7天添加到当前日期,如此

default: new Date(+new Date() + 7*24*60*60*1000)

甚至喜欢这个

default: +new Date() + 7*24*60*60*1000