HdN8
HdN8

Reputation: 3179

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.

Upvotes: 39

Views: 61585

Answers (2)

Viktor Kireev
Viktor Kireev

Reputation: 1240

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)

Upvotes: 41

Akhmedzianov Danilian
Akhmedzianov Danilian

Reputation: 947

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

This will be enough

Upvotes: 67

Related Questions