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.

Similar Reads

Prerequisites

MongoDB Basics Mongoose Schema...

Types of mongoose validation:

In Mongoose there are two types of validation:...

1. Built-in validators:

A. Required validator: A schema uses required whenever it is mandatory to fill that field with any value....

2. Custom validators

In addition to the built-in validators, you can define custom validators. In custom validation, a validation function is passed along with the declaration. Defining a custom validator involves creating a specialized function within the schema’s field definition to ensure that the data inserted or updated meets specific criteria beyond the standard validation rules offered by Mongoose....

Steps to create node application And Installing Mongoose:

Step 1: Create a node application using the following command:...