Open In App

Mongoose SchemaType.prototype.default() API

Last Updated : 06 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose SchemaType.prototype.default() method of the Mongoose API is used on the SchemaType object. It allows us to set the default value for the field in schema. Using this method we can provide default value to any path in the schema in the form of literal values or functions. The value we provide will be cast as per the type we have provided to a particular field or path. Let us understand default() method using an example.

Syntax:

schemaTypeObject.path( <path> ).default( <function/value>);

Parameters: This method accepts one single parameter as described below:

  • function/value: It is used to specify the default value for the field.

Return Value: This method returns the set default value for the field and sets default value for the field or path of SchemaType. 

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 default() method. In this example, we have defined studentSchema as having three attributes or fields name, age, and rollNumber. We are using the default() method on rollNumber path for returning the default value as a random integer. In the end, we can notice while creating a new object of the Student model we are not providing any value for rollNumber field, and in the database default value, i.e random integer value is reflected for rollNumber field.

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 },
    age: { type: Number },
    rollNumber: { type: Number },
});
 
studentSchema.path('rollNumber')
    .default(Math.ceil(Math.random() * 100))
 
const Student = connectionObject
    .model('Student', studentSchema);
 
Student.create({ name: 'Student1', age: 20 })
.then(newDocument => {
    console.log(newDocument);
})


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

node app.js

Output:

Note: The value for rollNumber field may differ for you because I am using random() method, which on every execution returns new integer value.

{
  name: 'Student1',
  age: 20,
  rollNumber: 9,
  _id: new ObjectId("63a40a1065e8951038a391b1"),
  __v: 0
}

GUI Representation of the Database using Robo3T GUI tool.

 

Example 2: In this example, we are returning the default value for rollNumber field using an arrow function. Along with that, we have set default values for the age field as well. In the end, we are just providing the value for the name field while creating a new document object of a Student model, and we are getting the expected result, default values are populating in the database.

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 },
    age: { type: Number, default: 18 },
    rollNumber: { type: Number },
});
 
studentSchema.path('rollNumber').default(() => {
    return 100 + Math.ceil(Math.random() * 100)
})
 
const Student = connectionObject
    .model('Student', studentSchema);
 
const newStudent = new Student({ name: 'Student2' });
 
newStudent.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: 'Student2',
    age: 18,
    _id: new ObjectId("63a40c193c8fe434f7effe5a"),
    rollNumber: 176,
    __v: 0
  }

GUI Representation of the Database using Robo3T GUI tool.

 

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads