Assigning a function as default in mongoose schema does not work

I am struggling to assign a default value for a field living in my model.
As per your doc, i can assign a static value.
But assigning a function, which is supported by mongoose, does not seem to work there.

My problem:
Assigning a function instead of a value in mongoose schema does not assign default value when in the form creation interface.

Expected behavior

The creation form field is populated with default value returned by the function.

Actual behavior

Form field is empty.

Hello @ThibaultRizzo,

Thanks for your message and welcome to our community! :raised_hands:

Can you please share with us your model definition (so that we can see what default function you’re trying to use and we might be able to reproduce the issue)?


Thank you for your reply!

Here is my schema:

       let schema = new mongoose.Schema({
            takenAt: { type: Date, required: false }, // I wish to add -> default:
            reportedAt: { type: Date, required: false },
            expirationDate: { type: Date, required: false }, 
            reportSentAt: { type: Date, required: false }, 
            reportReadAt: { type: Date, required: false } 
        }, {
            timestamps: true,
            usePushEach: true,
            toJSON: { virtuals: true }

@ThibaultRizzo I just made a test with this:

  'takenAt': {
    type: Date,

and it worked.

Is it working on your side as well?

If you do that, the value will be frozen (will stay 16/12/2020 a month from now), thus the need to evaluate the function at runtime.

:face_with_hand_over_mouth: My mistake, sorry, you’re right!

So I’ve tried again with this:

  'takenAt': {
    type: Date,

and I realised that it actually worked on my side.
Actually the date in the form is not filled (what value could be printed as the record was not created yet!) but once the record is created, the date is correctly filled.

Can you tell me if you observe the same behaviour? Does it suit your need?


Indeed, this works as expected! Thank you!

So just as a side-question, there is no way yet to add some non-static (evaluated at runtime) default values to the creation/edition forms?

@ThibaultRizzo I’m not sure to understand your side-question :roll_eyes:.
Could you please give me a example of what you’re trying to acheive?