Search code examples
node.jsdatabasemongodbnosqlmongodb-schema

Is the value of `null` allowed for fields that are required?


In MongoDB, what does it mean to have the required = true condition for a field in a collection?

Can the value be null?


Solution

  • 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