Open In App

Mongoose Schematype.checkRequired() API

Improve
Improve
Like Article
Like
Save
Share
Report

The Schematype.checkRequired() method of the Mongoose API is used to set and get the checkRequired() function. It overrides the required property validator and can be used to skip the required check. Let us understand the Schematype.checkRequired() method using example.

Syntax:

Schema.Types.String.checkRequired( function );

Parameters: This method accepts a single parameter as mentioned above and described below:

  • function: It is the function that performs the validation operation.

Return Value: This method returns the input or the set function.

Setting up Node.js application:

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: In this example, we have established a database connection using mongoose and defined model over userSchema, having two columns or fields “name”, and “age”. We have also defined getter function as a checkRequired() which is always returns true. This makes it possible to create a new document even after the name field is an empty string, even though it is a required field.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        get: mongoose
            .SchemaTypes
            .String
            .checkRequired(value => { return true }),
        required: true
    },
    age: {
        type: Number
    },
});
  
const User = mongoose.model('User', userSchema);
  
User.create({ name: '', age: 25 }).then(user => {
    console.log(user)
})


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: '',
  age: 25,
  _id: new ObjectId("6384a8ec353b83429bbdf0df"),
  __v: 0
}

GUI Representation of the Database using Robo3T GUI tool:

 

Example 2: In this example, we have established a database connection using mongoose and defined model over userSchema, having two columns or fields “name”, and “age”. We have also defined setter function as a checkRequired() which is conditionally checking if value of name attribute is empty. This returns either “Default Value” or the provided value if it is not empty.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        set: mongoose
  
            .SchemaTypes
            .String
            .checkRequired(value => {
                return (value.length <= 0 ? 'Default Value' : value)
            }),
        required: true
    },
    age: {
        type: Number
    },
});
  
const User = mongoose.model('User', userSchema);
  
const user = new User({ name: '', age: 28 })
user.save()
console.log(user)


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: 'Default Value',
  age: 28,
  _id: new ObjectId("6384a5ababbb876122181833")
}

GUI Representation of the Database using Robo3T GUI tool:

 

Example 3: In this example, we have also defined a setter function as a checkRequired() which is conditionally checks if the value of the name attribute is empty, thereby returning “Default Value” or the provided value if it is not empty. In this example, we are creating a new document “User3”, and we can see the same in database.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        set: mongoose
            .SchemaTypes
            .String
            .checkRequired(value => {
                return (value.length <= 0 ? 'Default Value' : value)
            }),
        required: true
    },
    age: {
        type: Number
    },
});
  
const User = mongoose.model('User', userSchema);
  
const user = new User({ name: 'User3', age: 30 })
user.save()
console.log(user)


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: 'Default Value',
 age: 28,
 _id: new ObjectId("6384a5ababbb876122181833")
}

GUI Representation of the Database using Robo3T GUI tool:

 

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



Last Updated : 08 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads