Open In App

Mongoose Virtuals

Improve
Improve
Like Article
Like
Save
Share
Report

Virtuals are document properties that do not persist or get stored in the MongoDB database, they only exist logically and are not written to the document’s collection.

With the get method of virtual property, we can set the value of the virtual property from existing document field values, and it returns the virtual property value. Mongoose calls the get method every time we access the virtual property.

Installing Module:

Step 1: You 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 2: 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

Implementation of Get Method:

Filename: app.js

Javascript




// 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

Explanation: Here schema contains fields name.first and name.last and has one virtual property name.full. Whenever name.full is accessed, the get method is called, and we get the fullname as a concatenation of first and last name. Hence, whenever we have to get the full name, we don’t have to access the firstname and lastname separately and concatenating them, instead, we can get them easily through the virtual property.

With the set method of virtual property, we can set the value of existing document fields from the value of the virtual property. 

Implementation of Set Method:

Filename: index.js

Javascript




// 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

Explanation: Here when the user saves the document using virtual property name.full, the set function automatically sets the fields name.first and name.last field values using name.full. Hence, with the help of virtual property, we didn’t need to provide each field separately for creating a document.



Last Updated : 24 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads