Open In App

Mongoose SchemaType.prototype.validate() API

Mongoose is a MongoDB object modeling and handling for a node.js environment.

Mongoose SchemaType validate is a SchemaType method that allows us to validate document paths before saving those to the DB. Let’s understand more about this with some examples.



Creating node application And Installing Mongoose:

Step 1: Create a node application using the following command:



mkdir folder_name
cd folder_name
npm init -y
touch main.js

Step 2: After creating the ReactJS application, Install the required module using the following command:

npm install mongoose

Project Structure: It will look like the following.

 

Example 1: In this example, we will create a validation function at a particular schema level that will allow us to validate if the name of the new schema instance created matches the value “John Doe”.

Filename: main.js




const mongoose = require('mongoose')
  
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : 
    console.log('Connected to database'));
  
function validator(val) {
    return val === 'John Doe';
}
  
const personSchema = new mongoose.Schema({
    name: {
        type: String,
        validate: validator
    },
});
  
const Person = mongoose.model('Person', personSchema);
const person1 = new Person({ name: 'John' });
(async function () {
    await person1.validate();
})()

Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

Example 2: In this example, we will create a validation function at a particular schema level that will allow us to validate if the name of the new schema instance created matches the value “John Doe”, and this time we will add our custom message to log in the console.

Filename: main.js




const mongoose = require('mongoose')
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true 
}, err => err ? console.log(err) : 
    console.log('Connected to database'));
  
function validator (val) {
  return val === 'John Doe';
}
const custom = [validator, 'Uh oh, 
    {PATH} does not equal "John Doe".']
const personSchema = new mongoose.Schema({
    name: {
      type: String,
      validate: custom
    },
});
  
const Person = mongoose.model('Person', personSchema);
const person1 = new Person({ name: 'John' });
(async function () {
  await person1.validate();
})()

Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

Reference: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-validate


Article Tags :