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.
As mentioned by user whoami, mongoose only sets defaults on insert. If you are using mongoose 4. x and up and MongoDB 2.4. 0 and up you can opt-in to setting default values on update too.
The setDefaultsOnInsert Option Mongoose also sets defaults on update() and findOneAndUpdate() when the upsert option is set by adding your schema's defaults to a MongoDB $setOnInsert operator. You can disable this behavior by setting the setDefaultsOnInsert option to false .
When you create a user document, Mongoose will cast the value to a native JavaScript date using the Date() constructor. const user = new User({ name: 'Jean-Luc Picard', lastActiveAt: '2002-12-09' }); user. lastActiveAt instanceof Date; // true. An invalid date will lead to a CastError when you validate the document.
default: () => Date.now() + 7*24*60*60*1000
This will be enough
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With