Open In App

Mongoose SchemaType.prototype.required() API

Last Updated : 26 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose SchemaType.prototype.required() method of the Mongoose API is used on the SchemaType object. It allows us to set validator on the field for schema. Using this method we can set validator’s for the SchemaType fields. Let us understand required() method using an example.

Syntax:

schemaTypeObject.required( <boolean/function/object> );

Parameters: This method accepts two parameters as described below:

  • required: It is used to enable or disable the required property for the field.
  • message: It is used to specify the error message.

Return Value: This method returns SchemaType object.

Setting up Node.js Mongoose Module:

Step 1: Create a Node.js application using the following command:

npm init

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

npm install mongoose

Project Structure: The project structure will look like this: 

 

Example 1: The below example illustrates the functionality of the Mongoose SchemaType required() method. In this example, we have defined studentSchema having three attributes or fields name, age, and rollNumber. At the end, name field is required and mandatory to have some value while creating objects of StudentModel. That is why we are getting validation error as we have not provided value for name field while creating StudentModel object.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const studentSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: Number,
    rollNumber: { type: Number }
});
  
const StudentModel = 
    connectionObject.model('Student', studentSchema);
  
const doc = new StudentModel({ age: 20, rollNumber: 101 });
  
doc.save((result => {
    console.log(result)
}))


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

Error: Student validation failed: name: Path `name` is required.

Example 2: The below example illustrates the functionality of the Mongoose SchemaType required() method. In this example, we have defined studentSchema having three attributes or fields name, age, and rollNumber. At the end, name field and rollNumber field is required and mandatory to have some value while creating objects of StudentModel.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const studentSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: Number,
    rollNumber: {
        type: Number, required: (() => {
            return this.age >= 18
        })
    }
});
  
const StudentModel = 
    connectionObject.model('Student', studentSchema);
  
const document = new StudentModel({ name: 'Student 1',
    age: 22, rollNumber: 101 });
document.save().then(document => {
    console.log(document);
})


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

{
    name: 'Student 1',
      age: 22,
      rollNumber: 101,
      _id: new ObjectId("63a3630fc9bec4d7e98de925"),
      __v: 0
}

Example 3: The below example illustrates the functionality of the Mongoose SchemaType required() method. In this example, we have defined studentSchema having three attributes or fields name, age, and rollNumber. At the end, name field is always required but rollNumber field is required and mandatory to have some value conditionally while creating objects of StudentModel.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const studentSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: Number,
    rollNumber: {
        type: Number, required: (() => {
            return this.age >= 18
        })
    }
});
  
const StudentModel = 
    connectionObject.model('Student', studentSchema);
  
const document2 = 
    new StudentModel({ name: 'Student 2', age: 16 });
      
document2.save().then(document2 => {
    console.log(document2);
})


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

{
    name: 'Student 2',
      age: 16,
     _id: new ObjectId("63a36373c69cbe92435273c0"),
      __v: 0
}

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads