Open In App

Mongoose Schemas Virtuals

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Syntax:

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

Parameters:

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

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: 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.

Javascript




// Require the mongoose module
const mongoose = require('mongoose');
  
// Path to our cloud DataBase
  
// 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

Example 2: The below example illustrates the functionality of the Mongoose Schema virtuals. In this example, we will define the virtuals using the virtual method.

Javascript




// Require the mongoose module
const mongoose = require('mongoose');
  
// Path to our cloud DataBase
  
// 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

Reference: https://mongoosejs.com/docs/guide.html#virtuals



Last Updated : 11 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads