DEV Community

Cover image for Mongoose Virtuals(Schema/Model)#clear concept of Virtuals
swapnanilWebDeveloper
swapnanilWebDeveloper

Posted on

Mongoose Virtuals(Schema/Model)#clear concept of Virtuals

Here is example of virtuals in Schema Model.Go through it deeply.

Follw the link below to get the full code on my git hub account

Click on this for full code in gitHub

const mongoose = require('mongoose');

main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://127.0.0.1:27017/employeeData');

  const employeeSchema = new mongoose.Schema({
    name: {
      first: { type : String},
      last: {type : String},
    },
    job : {
        domain : { type : String},
        experience : { type : Number},
        company : { type : String}
    }
  }, 

Enter fullscreen mode Exit fullscreen mode

1) At first Create a folder Virtuals_Schema and then create
virtuals.js (file) inside it.
2) Then Open your command-prompt and start your mongoshell and also create connection to MongoDBCompass and then Start writing your code into visual studio code editor.
3) First create connection with the mongoDB database and create a database called "employeeData" then create Schema called "employeeSchema".
4)Inside this Schema define two nested properties called "name" and "job" . In the 'name' property there are "first" and "last" two embeded properties and similar to "job" : "domain" , "experience" and "company" three embeded properties.

{
    virtuals: {
      fullName: {
        get() {
          return "Full name of the employee : "+this.name.first + ' ' + this.name.last;
        }
      },
      jobDescription : {
         get() {
             let JD;

             JD = this.name.first+" "+this.name.last+ " is working as : "+this.job.domain+", with a experience of : "+this.job.experience+
                   " years , in company : "+this.job.company;
            return JD;
         }
      }
    }
 });
Enter fullscreen mode Exit fullscreen mode

5)Now we have created two virtuals called "fullName" and "jobDescription" .
6)In the "fullName" virtual we have returned this.name.first and this.name.last concatinated string value; Now If any document calls this virtual with = ".fullName" it will get the returned value of firstName and lastName merged with each other.
ex-> Full name of the employee : Mayuk Mukherjee.

7)In the second virtual jobDescription we have get function where five document-values are merged and inserted into variable called JD. Five srtings are =>
this.name.first, this.name.last, this.job.domain, this.job.experience, this.job.company

 const Employee = mongoose.model('Employee', employeeSchema);

  await Employee.insertMany([
       {
         name : {
               first : "Mayuk",
               last : "Mukherjee",
           },
        job : {
            domain : "MERN Stack Developer",
            experience : 7,
            company : "DELL Co. Technologies"
        }
       },
       {
        name : {
              first : "Suryendu",
              last : "Sarkar",
          },
       job : {
           domain : "ASP.NET Developer",
           experience : 11,
           company : "Mint GREEN Solutions"
       }
      }
  ])

Enter fullscreen mode Exit fullscreen mode

8) Then create a model called Employee which is created through a reference of schema called "employeeSchema".
9) Then use insertMany([ {/document1/} , {/document2/} , {/document3/} ....]) , method to insert multiple documents.

   const allEmployee = await Employee.find({});
   console.log(allEmployee);

   console.log(allEmployee[0].fullName);
   console.log(allEmployee[0].jobDescription);

   console.log(allEmployee[1].fullName);
   console.log(allEmployee[1].jobDescription);
}

Enter fullscreen mode Exit fullscreen mode

10)Now we will write some code with find({}) query on Employee Model aand gather all the documents that we have inserted into Employee model.
11) This data that have been collected by find() is assigned to a variable called allEmployee as array of objects => [{}, {}]; where each document is considered as a single object .
12) Now to access these specific documents we will use allEmployee[index_no] => allEmployee[0] , allEmployee[1].
13) To access the virtuals for a specific document we will write our code like => allEmployee[0].fullName //allEmployee[1].fullName // allEmployee[0].jobDescription // allEmployee[1].jobDescription.
14) Now all the code has been completed and now let's see wht is the output.


PS C:\Users\USER\Downloads\mongoExpress\Schema_Virtuals> node src/virtuals_3.js
[
  {
    name: { first: 'Mayuk', last: 'Mukherjee' },
    job: {
      domain: 'MERN Stack Developer',
      experience: 7,
      company: 'DELL Co. Technologies'
    },
    _id: new ObjectId('65c4e414ea6d2c6b55a85619'),
    __v: 0
  },
  {
    name: { first: 'Suryendu', last: 'Sarkar' },
    job: {
      domain: 'ASP.NET Developer',
      experience: 11,
      company: 'Mint GREEN Solutions'
    },
    _id: new ObjectId('65c4e414ea6d2c6b55a8561a'),
    __v: 0
  }
]
Full name of the employee : Mayuk Mukherjee
Mayuk Mukherjee is working as : MERN Stack Developer, with a experience of : 7 years , in company : DELL Co. Technologies
Full name of the employee : Suryendu Sarkar
Suryendu Sarkar is working as : ASP.NET Developer, with a experience of : 11 years , in company : Mint GREEN Solutions

Enter fullscreen mode Exit fullscreen mode

Look at the output and analyse this code by yourself

MongoDb compass Graphical view of your database , collection, document

Top comments (0)