Built-in validators
A. Required validator: A schema uses required whenever it is mandatory to fill that field with any value.
Required validator takes an array with 2 items, first a Boolean var and a message to return the validation if it fails.
required: [true, “user name is required”]
we can also specify the Required validator without custom error message,
required: true
B. Unique validator: Unique is not a validator, but an option.
If the unique option is set, Mongoose will require each document to have a unique value for each path.
Unique option takes an array with 2 items, first a Boolean var and a custom error message.
unique: [true, 'email already exists']
we can also specify unique option without custom error message,
unique: true
Mongoose Validation
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Validation is essentially a customizable middleware that gets defined inside the SchemaType of Mongoose schema. It automatically fires off before a document is saved in the NoSQL DB. Validation can also be run manually using doc.validate(callback) or doc.validateSync() methods. Let’s understand more about this with the help of some examples.