Open In App

Mongoose Schemas Virtuals

Last Updated : 28 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Virtuals are a powerful feature in Mongoose that allow us to add attributes to documents without actually storing them in the database. These properties can be dynamically calculated based on other fields, making it easier to manage and manipulate your data. In this comprehensive article, we’ll dive into Mongoose Schema Virtuals, explaining how to use virtuals for computed properties in your Mongoose models.

What are Mongoose Schema Virtuals?

Mongoose Schemas Virtuals are document attributes that only exist logically and are not written to the document's collection in the MongoDB database. They do not persist or get stored there. When we access the virtual property, Mongoose calls the get method.

Virtual property setters are applied before other validation. For example, a virtual property can be used to combine first and last names into a full name, or format a date field. Virtuals are helpful for transforming or combining data without altering the actual structure of the database.

Syntax:

schema({
virtuals: {
propertyName: 'Program Logic'
}
});

Parameters:

  • propertyName: It is the name of the property which you want to define.

How Does Mongoose Virtuals Work?

Virtual properties in Mongoose allow us to create computed fields that appear like regular properties of your schema. They do not persist to the database, but are dynamically computed based on the document’s data when accessed. Virtuals can be used with both the get() and set() methods.

  1. Get Method: The get() method is used to retrieve and return a virtual property. It allows you to create a calculated field based on the existing document values.
  2. Set Method: The set() method allows you to set the value of virtual properties and automatically update corresponding fields.

How to Set Up Mongoose Virtuals

Before we dive into examples, you need to set up a Node.js project and install Mongoose. Once installed, Mongoose provides an easy way to define and manage virtuals within your schemas.

Installation of mongoose module:

You can visit the link to Install mongoose module. You can install this package by using this command.

npm install mongoose

 After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.

node index.js

Example 1: Using the Get Method to Create a Full Name

The below example illustrates the functionality of the Mongoose Schema virtuals property. In this example, we have defined a virtual named fullName on schema which will return a string. We will define the virtuals using this example schema options.

Filename: app.js

// Require the mongoose module
const mongoose = require('mongoose');

// Path to our cloud DataBase
const url = "mongodb://localhost:27017/GFG"

// Connecting to database
mongoose.set('strictQuery', false);

mongoose.connect(url)
.then((ans) => {
console.log("Connected Successful")
})
.catch((err) => {
console.log("Error in the Connection")
})

// Calling Schema class
const Schema = mongoose.Schema;

// Creating Structure of the model
const schema = new Schema({
firstName: {
type: String,
require: true,
},
lastName: {
type: String,
require: true,
}
},
{
virtuals: {
fullName: {
get() {
return this.firstName +
' ' + this.lastName;
}
}
}
});

// Compile our model
const Person = mongoose.model('Person', schema);

// Create a model
const person = new Person(
{ firstName: 'Sam', lastName: 'Snehil' }
);

// Using the virtuals function
console.log(
'FullName without concatenation: ',
person.firstName + ' ' + person.lastName);
console.log(
'Full Name with virtuals: ' + person.fullName
)

Output:

FullName without concatenation:  Sam Snehil
Full Name with virtuals: Sam Snehil
Connected Successful

Explanation: In this example, we defined a virtual property fullName that combines the firstName and lastName fields. When we access person.fullName, the get() method is triggered, which dynamically returns the full name as a combination of both fields.

Example 2: Using the Set Method to Split a Full Name into First and Last Name

In this example, we use the set() method to split a full name into firstName and lastName. When the virtual property fullName is set, the set() method automatically updates the firstName and lastName fields.

Filename: index.js

// Require the mongoose module
const mongoose = require('mongoose');

// Path to our cloud DataBase
const url = "mongodb://localhost:27017/GFG"

// Connecting to database
mongoose.set('strictQuery', false);

mongoose.connect(url)
.then((ans) => {
console.log("Connected Successful")
})
.catch((err) => {
console.log("Error in the Connection")
})

// Calling Schema class
const Schema = mongoose.Schema;

// Creating Structure of the model
const schema = new Schema({
name: String,
address: String,
});

// Creating the model
schema.virtual('Introduce').get((a, b) => {
return this.name + ' is from ' + this.address;
})
.set((v) => {
let temp1 = v.split(' ');
this.name = temp1[0];
this.address = temp1[1];
})

// Compile our model
const Person = mongoose.model('Person', schema);

// Create a model
const person = new Person({});
person.Introduce = 'Sam NewDelhi';

// Using the virtuals function
console.log(person.Introduce)

 Output:

Sam is from NewDelhi
Connected Successful

Explanation: In this example, when you set person.fullName, the set() method is called to split the string into name and address fields. The get() method is used to access and display the full name.

Why Use Mongoose Virtuals?

  1. Efficient Data Handling: Virtuals help keep your database clean by allowing you to compute data dynamically without storing it in the database.
  2. Cleaner Code: They allow you to encapsulate logic for computed properties, such as concatenating names, calculating totals, or formatting data, directly within the schema.
  3. Improved Data Integrity: Virtuals ensure that derived fields are always consistent, making your application logic easier to maintain.

Conclusion

Mongoose Virtuals are a powerful feature for adding computed fields to your MongoDB documents without actually storing them in the database. They allow you to manage complex data transformations and calculations within your Mongoose models efficiently. By using the get() and set() methods, you can streamline data handling and ensure better code organization. Virtuals are particularly useful for derived data like full names, addresses, or any field that combines or formats multiple pieces of information.


Next Article

Similar Reads