In a mongoose schema such as:
JavaScript
x
27
27
1
var EventSchema = new Schema({
2
title: {
3
type: String,
4
default: '',
5
trim: true,
6
required: 'Title cannot be blank'
7
},
8
description: {
9
type: String,
10
default: '',
11
trim: true
12
},
13
start: {
14
type: Date,
15
default: Date.now,
16
required: 'Must have start date - default value is the created date'
17
},
18
end: {
19
type: Date,
20
default: Date.now + 7 Days, // Date in one week from now
21
required: 'Must have end date - default value is the created date + 1 week'
22
},
23
tasks: [{
24
type: Schema.ObjectId,
25
ref: 'Task'
26
}]
27
});
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
JavaScript
1
2
1
default: new Date(+new Date() + 7*24*60*60*1000)
2
or even like this
JavaScript
1
2
1
default: +new Date() + 7*24*60*60*1000
2
UPDATE
Please check the @laggingreflex comment below. You need to set function as default value:
JavaScript
1
2
1
default: () => new Date(+new Date() + 7*24*60*60*1000)
2