Using Mongoose Validation and Custom Validator
Using Mongoose Validation and Custom Validator
Mongoose is a popular ODM (Object Data Modeling) library that provides ease of working with MongoDB on Node.js. With Mongoose, when you define your data models (schemas), you can easily prevent saving incorrect or incomplete data to the database thanks to its built-in validation support. In addition, you can define your own custom validator functions to implement project-specific rules. In this article, we discuss the topics of Mongoose Validation and Custom Validator with technical details.
What is Mongoose Validation and How Does It Work?
Mongoose validation is a mechanism that checks whether a document meets certain rules before being saved into the database. With Mongoose validation you can take advantage of built-in validation types for a property such as required, minLength, maxLength, min, max, match (regex), enum. It's also possible to customize error messages to provide more descriptive notifications to the user.
Example: Simple Use of Mongoose Validation
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: [true, 'Username is required!'],
minlength: [3, 'Username must be at least 3 characters!']
},
age: {
type: Number,
min: [18, 'Age must be 18 or older!']
}
});
const User = mongoose.model('User', userSchema);
In this example, the username field is required and must be at least 3 characters long. The age field cannot be less than 18. These validation rules are automatically checked when saving a document.
Using a Custom Validator
Sometimes standard validation rules may not be sufficient and you may need to define a Mongoose Custom Validator. With a custom validator, you can add custom validation rules for a field using any JavaScript function you like.
Example: Email Check with Mongoose Custom Validator
const emailRegex = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
const userSchema = new mongoose.Schema({
email: {
type: String,
validate: {
validator: function(v) {
return emailRegex.test(v);
},
message: props => `${props.value} is not a valid email address!`
},
required: [true, 'Email is required!']
}
});
In the example above, a custom validator that checks the email field using regex is used. If the entered email is incorrect, a custom error message is returned.
Async Validator Example (Mongoose >=4.9.0)
const userSchema = new mongoose.Schema({
username: {
type: String,
validate: {
validator: async function(value) {
// Check if the username is unique
const count = await this.model('User').countDocuments({ username: value });
return count === 0;
},
message: 'This username is already taken!'
},
required: true
}
});
In this example, with an asynchronous custom validator, it is ensured that the username is unique. Thanks to Mongoose validation and custom validators, you achieve high data quality and security.
Mongoose Validation and Custom Validator Conclusion
In your own projects, you can easily implement both standard and advanced validations suited to your needs with Mongoose validation and custom validator. You should definitely take advantage of these features that Mongoose offers for structured data and superior error management. Thus, you can develop secure, scalable, and accurate data-driven applications on MongoDB.

Yorum Gönder