In MongoDB, what does it mean to have the required = true condition for a field in a collection?
required = true
Can the value be null?
null
2
No value cannot be null, required: true will throw an error if null value is passed to the field on which required is implemented.
required: true
required
As per Mongoose documentation on required
By default, a value satisfies the required validator if val != null (that is, if the value is not null nor undefined)
val != null
Keep in mind, that’s the default behavior, so there is a possibility for custom implementation.
required = true seems to be using Mongoose, so it doesn’t accepts null values.
By default, a value satisfies the required validator if val != null (that is, if the value is not null nor undefined).
Can be found in their docs: https://mongoosejs.com/docs/api.html#schematype_SchemaType-required
MongoDB has a similar approach, but you declare all fields in the required option
i.e.:
... required: [ "name", "year", "major", "address" ] ...
More can be found here
Click here to cancel reply.
2
Answers
No value cannot be
null
,required: true
will throw an error ifnull
value is passed to the field on whichrequired
is implemented.As per Mongoose documentation on required
Keep in mind, that’s the default behavior, so there is a possibility for custom implementation.
required = true
seems to be using Mongoose, so it doesn’t accepts null values.Can be found in their docs: https://mongoosejs.com/docs/api.html#schematype_SchemaType-required
MongoDB has a similar approach, but you declare all fields in the
required
optioni.e.:
More can be found here