Mongoose Validation
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Validation is essentially a customisable middleware that gets defined inside the SchemaType of mongoose schema. It automatically fires off before a document is saved in the noSQL DB. Validation can also be run manually using doc.validate(callback) or doc.validateSync() methods. Let’s understand more about this with the help of 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 use a “required” validator to check whether a value is passed to the document or not before saving it to the DB.
Filename: main.js
Javascript
const mongoose = require( 'mongoose' ) // Database connection 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 } }); const Person = mongoose.model( 'Person' , personSchema); const person = new Person({}); (async () => { try { await person.save(); } catch (err) { console.log(err) } })(); |
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 a “required” and a “min” validator to check whether a value is passed to the document or not and whether the value is above a threshold number before saving it to the DB.
Filename: main.js
Javascript
const mongoose = require( 'mongoose' ) // Database connection dbName: 'event_db' , useNewUrlParser: true , useUnifiedTopology: true }, err => err ? console.log(err) : console.log( 'Connected to database' )); const personSchema = new mongoose.Schema({ age: { type: Number, required: true , min: [18, 'Age must be 18 or above' ] } }); const Person = mongoose.model( 'Person' , personSchema); const person = new Person({ age: 16 }); (async () => { try { await person.save(); } catch (err) { console.log(err) } })(); |
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/validation.html
Please Login to comment...