Writing custom validators for Mongoose's schemas
Mongoose has several built-in validation rules. For instance, if you define a property with a schema type of string
and set it as required
, two validation rules will be executed, one that checks for the property to be a valid string
and another one for checking that the property is not null
or undefined
.
Custom validation rules and custom error validation messages can also be defined in Mongoose for having more control on how and when certain properties are accepted before they can be saved in the database.
Validation rules are defined in the schema. All schema types have a built-in validator required
which means it cannot contain undefined
or null
values. The required
validator can be of type boolean
, a function
, or an array
. For example:
path: { type: String, required: true } path: { type: String, required: [true, 'Custom error message'] } path: { type: String, required: () => true }
String schema types have the following...