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?
You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With