Mongoose Virtuals - GeeksforGeeks

24 May, 2021
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
Filename: app.js
Javascript
// Requiring moduleconst mongoose = require('mongoose');const express = require('express');const app = express();  // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG',    {        useNewUrlParser: true,        useUnifiedTopology: true,        useFindAndModify: false    });  // Constructing mongoose schemaconst userSchema = new mongoose.Schema({    name: {        first: String,        last: String    }});  // Setting virtual property using get methoduserSchema.virtual('name.full')    .get(function () {        return this.name.first + ' ' + this.name.last;    })  // Creating mongoose modelconst 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. 
Filename: index.js
Javascript
// Requiring moduleconst mongoose = require('mongoose');const express = require('express');const app = express();  // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG',    {        useNewUrlParser: true,        useUnifiedTopology: true,        useFindAndModify: false    });  // Constructing mongoose schemaconst userSchema = new mongoose.Schema({    name: {        first: String,        last: String    }});  // Setting the firstname and lastname using set methoduserSchema.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 modelconst 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.
MongoDB
Mongoose
Node.js-Methods
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
MongoDB Cursor
Create user and add role in MongoDB
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Express.js express.Router() Function
Node.js fs.readFile() Method