Skip to content
Advertisement

Mongoose date field – Set default to date.now + N days

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.

Advertisement

Answer

You can add 7 days converted to milliseconds to current date like this

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:

default: () => new Date(+new Date() + 7*24*60*60*1000)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement