I have a mongoose schema and I want to provide a default value but anytime I provide that, I run into an error. This is the schema object value I want to provide a default value for and how I currently pass it.
statusData: {
type: [
{
status: { ...trimmedString, required: false, default: 'new' },
createdAt: {
type: SchemaTypes.Date,
required: false,
default: Date.now
},
updatedAt: {
type: SchemaTypes.Date,
required: false,
default: null
},
},
],
default: [ {
status: 'new',
createdAt: Date.now,
updatedAt: null
}],
}
But I get this error every time.
validation failed: statusData.0.createdAt: Cast to date failed for value "[Function: now]" at path "createdAt""
any help on how I can provide a default value here
CodePudding user response:
You are currently casting a function to the default value, not the return of the function.
You also can't pass the return of the function straight in or it will reset the createdAt
every time to the current date.
Instead, add a callback function to the default value that returns Date.now()
createdAt: {
type: SchemaTypes.Date,
required: false,
default: () => Date.now()
},
Also, it wouldn't be a bad idea to pass immutable: true
to the createdAt value, since likely that should never change.