Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 843
HdN8 Avatar asked Apr 27 '15 14:04

HdN8


People also ask

Can we set default value in Mongoose Schema?

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.

How do I set default value in MongoDB Schema?

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 .

What is Date format in Mongoose?

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.


1 Answers

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

This will be enough

like image 146
Akhmedzianov Danilian Avatar answered Sep 18 '22 08:09

Akhmedzianov Danilian