DEV Community

Cover image for Mongoose Tutorial with Code and challenges # This code explains Virtuals in Schema/Model...
swapnanilWebDeveloper
swapnanilWebDeveloper

Posted on

Mongoose Tutorial with Code and challenges # This code explains Virtuals in Schema/Model...

This code is a simple example for virtuals

Here multiple properties merge to one single property

When there is nested data inside schema then we use virtuals to merge them into a newly created single property

lte's see how this code executes

  const mongoose = require('mongoose');

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

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

  const personSchema = new mongoose.Schema({
    name: {
      first: { type : String},
      last: {type : String},
    }
  }, {
    virtuals: {
      fullName: {
        get() {
          return this.name.first + ' ' + this.name.last;
        }
      }
    }
  });
Enter fullscreen mode Exit fullscreen mode

here we have defined a Schema called personSchema and this personSchema is defined one property "name" and this is a nested data with two other properties "first" & "last".
Then we have defined virtuals with a name called "fullName" which contains get() function .
This get() function returns "name.first" and "name.last" merged to a new property called 'fullName'.

  const Person = mongoose.model('Person', personSchema);
Enter fullscreen mode Exit fullscreen mode

"Person" is a model of the Schema "personShema"

  await Person.insertMany([
       {
         name : {
               first : "Mayuk",
               last : "Mukherjee",
           }
       }
  ])
Enter fullscreen mode Exit fullscreen mode

In the "person" model we have given two different values to nested properties "name.first" , "name.last" => "Mayuk" , "Mukherjee" repectively..

   const allPerson = await Person.find({});
   console.log(allPerson);

   console.log("full name is = "+allPerson[0].fullName);
}  

Enter fullscreen mode Exit fullscreen mode

Here by find() method which is a query we get the data and store it into a variable called allPerson. allperson is a array of object here and it has only one object as element and that's why allPerson[0] contains the document.

  [
  {
    name: { first: 'Mayuk', last: 'Mukherjee' },
    _id: new ObjectId('65c288e2bf32b1e144f31966'),
    __v: 0
  }
]
full name is = Mayuk Mukherjee
Enter fullscreen mode Exit fullscreen mode

Here's the expected output...

Top comments (0)