1

I have a Mongoose Schema where I am assigning a default value to a field by calling a function.

My schema

function fun(){
    let curr_time = moment().format();
    return curr_time;
};

let flagged_trans_schema = new Schema({
    time: {type: Date, default: fun},
});

I am facing a problem here, when I am writing default: fun() then the time field is not getting updated time, but when I am writing default: fun then time field value is updating every time.

Can anyone please tell me why it is happening?

1 Answer 1

6

Using default: fun() sets the default to the result of calling the fun function at the time the schema is declared. Just once, and the default will be that value for all newly created model instances (or, possibly, documents from the database that didn't have the time field set).

Using default: fun sets the default to reference the fun function, and Mongoose is smart enough to know that this means that it should call that function each time a new model instance is created.

Sign up to request clarification or add additional context in comments.

2 Comments

But the thing is my IDE which is webstorm is blacking out default line, don't know why it is doing?
I have no idea either, I don't use WebStorm myself. Try quoting default: "default" : fun

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.