Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

array default object mongoose schema

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""

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

any help on how I can provide a default value here

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading