Mongoose SchemaType.prototype.validators Property
Last Updated :
21 Feb, 2023
Mongoose is a MongoDB object modeling and handling for a node.js environment. The Mongoose SchemaType validators property is used to get the validators applied on a schema path of a mongoose schema.
Syntax:
SchemaType.prototype.validators
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 completing the Node.js 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 use this method to log the validators applied on the “name” mongoose schema path.
Filename: main.js
Javascript
const mongoose = require( 'mongoose' )
{
dbName: 'event_db' ,
useNewUrlParser: true ,
useUnifiedTopology: true
}, err => err ? console.log(err)
: console.log( 'Connected to database' ));
const personSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
age: {
type: Number,
}
});
const Person = mongoose.model( 'Person' , personSchema);
(async () => {
const validators = personSchema.path( 'name' ).validators
console.log({ validators });
})()
|
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 use this method to validate a particular age using the validators applied on the “age” mongoose schema path.
Filename: main.js
Javascript
const mongoose = require( 'mongoose' )
{
dbName: 'event_db' ,
useNewUrlParser: true ,
useUnifiedTopology: true
}, err => err ? console.log(err)
: console.log( 'Connected to database' ));
const personSchema = new mongoose.Schema({
name: {
type: String,
},
age: {
type: Number,
min: 20
}
});
const Person = mongoose.model( 'Person' , personSchema);
(async () => {
const validators = personSchema.path( 'age' ).validators
const res = validators[0].validator(28)
console.log({res});
})()
|
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-validators
Share your thoughts in the comments
Please Login to comment...