How to implement custom validation in Mongoose schemas in Node.js



Image not found!!

In Mongoose, you can implement custom validation for your schemas using the validate property. This property allows you to define a function that performs custom validation logic. Here's an example of how you can implement custom validation in Mongoose schemas in a Node.js environment:

javascript
const mongoose = require('mongoose'); // Create a Mongoose schema const userSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true, validate: { validator: function(value) { // Custom validation logic here // Return true if the value is valid, false otherwise return /^[a-zA-Z0-9]+$/.test(value); }, message: 'Username must only contain letters and numbers.' } }, email: { type: String, required: true, unique: true, validate: { validator: function(value) { // Custom email validation logic here // Return true if the value is valid, false otherwise return /\S+@\S+\.\S+/.test(value); }, message: 'Invalid email format.' } }, age: { type: Number, validate: { validator: function(value) { // Custom age validation logic here // Return true if the value is valid, false otherwise return value >= 18 && value <= 99; }, message: 'Age must be between 18 and 99.' } } }); // Create a Mongoose model const User = mongoose.model('User', userSchema); // Example usage const newUser = new User({ username: 'john_doe123', email: 'john@example.com', age: 25 }); newUser.save() .then(result => { console.log('User saved successfully:', result); }) .catch(error => { console.error('Error saving user:', error.message); });

In this example:

  1. The validate property is used within the schema to define a validation function for each field.
  2. The validator property in the validation object contains the custom validation function, which should return true if the value is valid and false otherwise.
  3. The message property in the validation object is used to specify a custom error message that will be displayed if the validation fails.

Remember to replace the custom validation logic in the example with your specific requirements for each field.