Adding validation with Mongoose
Validations in Mongoose are defined at the schema level. Validations can be set in both strings and in numbers. Mongoose provides us with built-in validation techniques for strings and numbers. Also, we can customize these according to our need as well. Since validations are defined in the schemas, they are triggered when we hit the save()
method for any document. If we only want to test these validations, we can do that as well by executing the validation method only via {doc}.validate()
.
validate()
is also middleware, which means it has control when we are executing some methods in an asynchronous way.
Default validations
Let's talk about some of the default validations that Mongoose provides us with. These are also called built-in validators.
required()
The required()
validator checks if the field we added this validation on has some value or not. Previously, in the User
model, we had this code:
var mongoose = require("mongoose"); var Schema = mongoose.Schema...