11

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?

Naor
  • 23,465
  • 48
  • 152
  • 268

1 Answers1

10

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

Farhan Tahir
  • 2,096
  • 1
  • 14
  • 27
  • what is the proposeof using required with default? if there is a default then what case the require should throw error? – adir abargil Apr 20 '21 at 14:52
  • 2
    @adirabargil from [the docs](https://mongoosejs.com/docs/defaults.html): **Note**: Mongoose only applies a default if the value of the path is strictly `undefined`. – Amit Beckenstein Jun 10 '21 at 07:10
  • 5
    @Farhan that's lame on Mongoose's part. IMO they should've checked for `null`/`undefined`, nothing more. – Amit Beckenstein Jun 10 '21 at 07:12