The Mongoose Schema API .prototype.virtual() method of the Mongoose API is used on the Schema object. It allows us to define virtual method and type over each schema with a specific name and method definition. Let us understand virtual() method using an example.
Syntax:
schemaObject.virtual( <name>, <options> );
Parameters: This method accepts two parameters as described below:
- name: It is used to specify the virtual method name over the schema
- options: It is used to specify various properties for that virtual method.
Return Value: This method can return any virtual type value.
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 Schema virtual() method. In this example, we have defined a virtual named example1 on studentSchema which is return a string.
Filename: app.js
// Require mongoose module const mongoose = require( "mongoose" );
// Set Up the Database connection const URI = "mongodb://localhost:27017/geeksforgeeks"
const connectionObject = mongoose.createConnection(URI, { useNewUrlParser: true ,
useUnifiedTopology: true ,
}); const studentSchema = new mongoose.Schema({
name: String,
rollNumber: Number
}); studentSchema.virtual( 'example1' ).get(() => {
return 'Virtual Method'
}); console.log(studentSchema.virtuals.example1.getters[0].call()); |
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
Virtual Method
Example 2: The below example illustrates the functionality of the Mongoose Schema virtual() method. In this example, we have defined a virtual named portNumber which is returning port number.
Filename: app.js
// Require mongoose module const mongoose = require( "mongoose" );
// Set Up the Database connection const URI = "mongodb://localhost:27017/geeksforgeeks"
const connectionObject = mongoose.createConnection(URI, { useNewUrlParser: true ,
useUnifiedTopology: true ,
}); const studentSchema = new mongoose.Schema({
name: String,
rollNumber: Number
}); studentSchema.virtual( 'portNumber' ).get(() => {
return 27017
}); console.log(studentSchema.virtuals.portNumber); |
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
VirtualType { path: 'portNumber', getters: [ [Function (anonymous)] ], setters: [], options: {} }
Reference: https://mongoosejs.com/docs/api/schema.html#schema_Schema-virtual