How to Validate Data in Mongoose: Simple Guide
In
mongoose, data validation is done by defining validation rules inside the Schema using built-in validators like required, minlength, and match. You can also create custom validation functions inside the schema to check data before saving it to the database.Syntax
In Mongoose, you define validation rules inside the Schema by specifying properties for each field. Common validators include required to make a field mandatory, minlength or maxlength for string length limits, and match for regex pattern matching. You can also add a validate property with a custom function for complex checks.
javascript
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true, minlength: 3 }, email: { type: String, required: true, match: /.+\@.+\..+/ }, age: { type: Number, min: 18, max: 65 }, password: { type: String, required: true, validate: { validator: function(v) { return /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/.test(v); }, message: props => `${props.value} is not a strong password!` } } });
Example
This example shows how to create a Mongoose model with validation rules and how Mongoose throws an error if data does not meet those rules.
javascript
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser: true, useUnifiedTopology: true }); const userSchema = new mongoose.Schema({ username: { type: String, required: true, minlength: 4 }, email: { type: String, required: true, match: /.+\@.+\..+/ }, age: { type: Number, min: 18 }, }); const User = mongoose.model('User', userSchema); async function createUser() { try { const user = new User({ username: 'abc', email: 'invalidemail', age: 16 }); await user.save(); } catch (error) { console.log('Validation Error:', error.message); } finally { await mongoose.connection.close(); } } createUser();
Output
Validation Error: User validation failed: username: Path `username` (`abc`) is shorter than the minimum allowed length (4)., email: Validator failed for path `email` with value `invalidemail`, age: Path `age` (16) is less than minimum allowed value (18).
Common Pitfalls
- Not calling
save()orvalidate()to trigger validation. - Using incorrect validator syntax or forgetting to return
trueorfalsein custom validators. - Ignoring asynchronous validation rules which require
asyncfunctions or callbacks. - Not handling validation errors properly, which can cause silent failures.
javascript
const schema = new mongoose.Schema({ name: { type: String, validate: function(value) { // Missing return statement causes validation to always pass /[A-Z]/.test(value); } } }); // Correct way const schemaFixed = new mongoose.Schema({ name: { type: String, validate: function(value) { return /[A-Z]/.test(value); } } });
Quick Reference
Here is a quick summary of common Mongoose validation options:
| Validator | Description | Example |
|---|---|---|
| required | Makes a field mandatory | { name: { type: String, required: true } } |
| minlength | Minimum string length | { name: { type: String, minlength: 3 } } |
| maxlength | Maximum string length | { name: { type: String, maxlength: 10 } } |
| min | Minimum number value | { age: { type: Number, min: 18 } } |
| max | Maximum number value | { age: { type: Number, max: 65 } } |
| match | Regex pattern match | { email: { type: String, match: /.+\@.+\..+/ } } |
| validate | Custom validation function | { password: { validate: { validator: fn, message: 'error' } } } |
Key Takeaways
Define validation rules inside the Mongoose schema to ensure data correctness.
Use built-in validators like required, minlength, max, and match for common checks.
Create custom validator functions for complex validation logic.
Always handle validation errors when saving documents to catch invalid data.
Remember to return true/false in custom validators and handle async validations properly.