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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →