Mongoose Virtuals

Last Updated : 8 Oct, 2025

Mongoose virtuals are fields that are not saved in the database. They are made from other data in the document, like combining first and last name to make a full name. The get method tells how to calculate the value, and it runs every time the virtual field is used.

How to Set Up Mongoose Virtuals

To use Mongoose Virtuals, we'll first need to set up a Node.js project and install the Mongoose package. Once Mongoose is installed, we can easily define schemas and add virtual properties for enhanced functionality.

Step 1: Create a new Node.js project:

mkdir mongoose-virtuals
cd mongoose-virtuals
npm init -y

Step 2: Install Mongoose

We can visit the link Install mongoose to get information about installing the mongoose module. You can install this package by using this command:

npm install mongoose

Step 3: Import Mongoose into your file:

After installing the mongoose module, you can import it into your file using the following code:

const mongoose = require('mongoose');

Database: Initially, we have an empty collection of users in the database GFG.

Initially, collection users is empty

Methods Of Mongoose Virtuals

Here are the methods of mongoose virtuals:

1. Get Method

The get() method of a virtual property allows us to retrieve a value based on existing document fields.

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

In this example, we'll use the get() method to create a virtual property that combines a user's first and last name into a full name. This approach makes it easier to retrieve and display the full name without manually concatenating the first and last name fields.

Filename: app.js

// Requiring module
const mongoose = require('mongoose');
const express = require('express');
const app = express();

// Connecting to database
mongoose.connect('mongodb://localhost:27017/GFG',
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false
    });

// Constructing mongoose schema
const userSchema = new mongoose.Schema({
    name: {
        first: String,
        last: String
    }
});

// Setting virtual property using get method
userSchema.virtual('name.full')
    .get(function () {
        return this.name.first + ' ' + this.name.last;
    })

// Creating mongoose model
const User = mongoose.model('user', userSchema);

const newUser = new User({
    name: {
        first: "David",
        last: "Beckham"
    }
})

newUser.save()
    .then(u => {
        console.log("USERNAME: ", u.name.full)
    })
    .catch(error => {
        console.log(error);
    })

Run app.js file using the following command:

node app.js

Output:

Output after executing app.js

Database: After the execution of the program, our database will look like this.

Collection users after executing app.js

In this example:

  • The schema has name.first and name.last fields.
  • It also has a virtual property name.full.
  • When name.full is accessed, the get method runs.
  • get combines first and last to return the full name.
  • This allows getting the full name directly without manually joining first and last.

2. Set Method

The set() method of a virtual property allows you to modify existing document fields based on the value provided for the virtual property. This is useful when you want to update fields without explicitly specifying each one.

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

In this example, we'll use the set() method to automatically split a full name into first and last name when the virtual property name.full is assigned a value. This approach allows you to update multiple fields with a single input, streamlining the process of handling and storing data.

Filename: index.js

// Requiring module
const mongoose = require('mongoose');
const express = require('express');
const app = express();

// Connecting to database
mongoose.connect('mongodb://localhost:27017/GFG',
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false
    });

// Constructing mongoose schema
const userSchema = new mongoose.Schema({
    name: {
        first: String,
        last: String
    }
});

// Setting the firstname and lastname using set method
userSchema.virtual('name.full')
    .get(function () {
        return this.name.first + ' ' + this.name.last;
    })
    .set(function (value) {
        var fname = value.split(' ');
        this.name.first = fname[0];
        this.name.last = fname[1];
    })

// Creating mongoose model
const User = mongoose.model('user', userSchema);

const newUser = new User({
    name: {
        full: "Dave Bautista"
    }
})

newUser.save()
    .then(u => {
        console.log("FIRSTNAME: ", u.name.first,
                    "\nLASTNAME:", u.name.last)
    })
    .catch(error => {
        console.log(error);
    })

Run index.js file using the following command:

node index.js

Output:

Output after executing index.js

Database: After the execution of the program, our database will look like this.

Collection users after executing index.js

In this example:

  • When saving a document using the virtual name.full, the set function runs.
  • The set function splits name.full into name.first and name.last.
  • This allows creating a document without providing first and last separately.
  • Virtuals simplify data handling by automating field updates.
Comment

Explore