Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose model required and with default

I created mongoose model with a field named "phoneNumber":

...
phoneNumber: {
    type: 'String',
    required: true,
    default: ''
},
...

Whenever I create a new record of that model, I got validation failed exception:

 Path `phoneNumber` is required

This is happens even though I set default value. What is incorrect?

like image 690
Naor Avatar asked Apr 21 '18 14:04

Naor


People also ask

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

What is default Mongoose?

Default values are applied when the document skeleton is constructed. This means that if you create a new document ( new MyModel ) or if you find an existing document ( MyModel. findById ), both will have defaults provided that a certain key is missing.

What is required true in Mongoose schema?

Mongoose has several built-in validators. All SchemaTypes have the built-in required validator. The required validator uses the SchemaType's checkRequired() function to determine if the value satisfies the required validator. Numbers have min and max validators.

Why Mongoose is required?

The benefit of using Mongoose is that we have a schema to work against in our application code and an explicit relationship between our MongoDB documents and the Mongoose models within our application. The downside is that we can only create blog posts and they have to follow the above defined schema.


1 Answers

You are setting the default value to empty string and in JavaScript empty string is a falsy value. Thus the required check fails and you get that validation message.

Read more about Falsy values at: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

like image 176
Farhan Tahir Avatar answered Sep 28 '22 05:09

Farhan Tahir