Skip to content
Related Articles
Open in App
Not now

Related Articles

Mongoose Schemas Virtuals

Improve Article
Save Article
Like Article
  • Last Updated : 11 Jan, 2023
Improve Article
Save Article
Like Article

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


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!