How to use Custom Validators In Mongoose
- Through the custom validators, we can impose on the specific validation rules that are not covered by the Onbuilt ones by Mongoose.
- This means that we can have more control over the data validation according to our needs which our application has.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
validate: {
validator: function(v) {
return v.length >= 3 && v.length <= 20;
},
message: props => `${props.value} is not a valid username! Must be between 3 and 20 characters.`
}
},
email: String
});
const UserModel = mongoose.model('User', userSchema);
Output:
If the validation fails for the username field, an error will be thrown with the specified message. Otherwise, no output is generated directly from registering the schema.
Explanation:
- We define a schema for a user with fields username and email.
- A custom validator is added to the username field, ensuring that its length falls within the specified range (3 to 20 characters).
How to Register Schema in Mongoose?
In Mongoose, schema registration is a crucial step in defining the structure of our MongoDB documents. In this article, We will go through the process of registering a schema in Mongoose by providing various methods with implementation to efficiently manage our data models.