DEV Community

Cover image for Mongoose Alias Schema with instance method# Diffuclty Exterme # Challange yourself
swapnanilWebDeveloper
swapnanilWebDeveloper

Posted on

Mongoose Alias Schema with instance method# Diffuclty Exterme # Challange yourself

1) Alias is a very important concept for those who want to master mongoose .
2) Alias provides you a shortcut path or a alternate path where you can get access to properties and values of documents.

To get more programs of mongoose and to boost your knowledge on mongoose you can follow this link of my GitHub account

click on this to get into github account

const mongoose = require('mongoose');

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

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

    const studentSchema = new mongoose.Schema({
        studentName : {
            type: String,
            alias: 'name',
        },
        studentEmail : {
            type : String,
            alias : 'email',
        },
        studentAddress : {
            state : { type : String, alias : "st"},
            district : { type : String, alias : "dist"},
            city : { type : String, alias : "ct"},
        },
        scienceMarks : {
            theoryPaper : { 
                physics : { type : Number, alias : "phTheo"},
                chemistry : { type : Number, alias : "chTheo"},
                mathematics : { type : Number, alias : "mtTheo"},
            },
            practicalPaper : {
                physics : { type : Number, alias : "phPrt"},
                chemistry : { type : Number, alias : "chPrt"},
                mathematics : { type : Number, alias : "mtPrt"},
            }
        }
    },
    {
          methods: {
             getStudentBioData() {
                 const bioData =  "name is : "+this.name+", email is : "+this.email;
                 return bioData; 
            },
             getStudentLocationData() {
                const locationData =  "Student is currently living in state : "+this.st+", at district is : "+this.dist+
                                       ", at city is : "+this.ct;
                return locationData; 
           },
            getStudentScienceMarks(){
                let physicsTotal, chemistryTotal , mathematicsTotal;
                physicsTotal = this.phTheo + this.phPrt;
                chemistryTotal = this.chTheo + this.chPrt;
                mathematicsTotal = this.mtTheo + this.mtPrt;

                this.getHelloStudents(this.name, physicsTotal + chemistryTotal + mathematicsTotal);

                return "Marks in physics = "+physicsTotal+", chemistry = "+chemistryTotal+", mathematics = "+mathematicsTotal;
            },
            getHelloStudents(stuName, totalMarks){
                let grade, average;
                average = (totalMarks / 3).toFixed(2);

                if(average >= 90){
                     grade = "Excellent";
                }
                else if(average >= 70 && average < 90){
                     grade = "Very Good";
                }
                else if(average >= 50 && average < 70){
                    grade = "Good";
               }
               else if(average >= 30 && average < 50){
                grade = "Pass";
               }
               else{
                 grade = "Fail";
               }

               console.log(stuName+" , has got total marks of = "+totalMarks+", average = "+average
                  + ",\n with a grade of : "+grade);
            }
          }
    }
    );

    const Student = mongoose.model('Student', studentSchema);

    await Student.insertMany([
        {
            name : "Mayuk Mukherjee",
            email : "Mayuk@gmail.com",
            st : "California",
            dist : "Ohio",
            ct : "Colorado",
            phTheo : 79,
            chTheo : 68,
            mtTheo : 77,
            phPrt : 18,
            chPrt : 16,
            mtPrt : 19,
        },
        {
            name : "Suryendu Sarkar", 
            email : "Suryendu@gmail.com",
            st : "Alabama",
            dist : "Denver",
            ct : "California",
            phTheo : 49,
            chTheo : 58,
            mtTheo : 58,
            phPrt : 12,
            chPrt : 18,
            mtPrt : 12
        },
        {
            name : "Aninda Mukherjee",
            email : "Aninda@gmail.com",
            st : "Alaska",
            dist : "Texas",
            ct : "Huston",
            phTheo : 54,
            chTheo : 59,
            mtTheo : 42,
            phPrt : 15,
            chPrt : 20,
            mtPrt : 14,
        },
        {
            name : "Sanlap Gadai",
            email : "Sanlap@gmail.com",
            st : "MAssachuttes",
            dist : "Ohio",
            ct : "Atlanta",
            phTheo : 66,
            chTheo : 61,
            mtTheo : 59,
            phPrt : 18,
            chPrt : 12,
            mtPrt : 14,
        },
    ]);

    const allStudent = await Student.find({});
    console.log(allStudent);

    console.log("total students number = "+allStudent.length+"\n");

    for(var i = 0; i < allStudent.length; i++){
         console.log(allStudent[i].getStudentBioData());
         console.log(allStudent[i].getStudentLocationData());
         console.log(allStudent[i].getStudentScienceMarks());
         console.log("\n");
    }
}

Enter fullscreen mode Exit fullscreen mode

Go through this code very carefully .
Check this output given below :


PS C:\Users\USER\Downloads\mongoExpress\Alias_Schema> node src/alias_2.js
[
  {
    studentAddress: { state: 'California', district: 'Ohio', city: 'Colorado' },
    scienceMarks: { theoryPaper: [Object], practicalPaper: [Object] },
    _id: new ObjectId('65c50e0667aa21025fa5f6dc'),
    studentName: 'Mayuk Mukherjee',
    studentEmail: 'Mayuk@gmail.com',
    __v: 0
  },
  {
    studentAddress: { state: 'Alabama', district: 'Denver', city: 'California' },
    scienceMarks: { theoryPaper: [Object], practicalPaper: [Object] },
    _id: new ObjectId('65c50e0667aa21025fa5f6dd'),
    studentName: 'Suryendu Sarkar',
    studentEmail: 'Suryendu@gmail.com',
    __v: 0
  },
  {
    studentAddress: { state: 'Alaska', district: 'Texas', city: 'Huston' },
    scienceMarks: { theoryPaper: [Object], practicalPaper: [Object] },
    _id: new ObjectId('65c50e0667aa21025fa5f6de'),
    studentName: 'Aninda Mukherjee',
    studentEmail: 'Aninda@gmail.com',
    __v: 0
  },
  {
    studentAddress: { state: 'MAssachuttes', district: 'Ohio', city: 'Atlanta' },
    scienceMarks: { theoryPaper: [Object], practicalPaper: [Object] },
    _id: new ObjectId('65c50e0667aa21025fa5f6df'),
    studentName: 'Sanlap Gadai',
    studentEmail: 'Sanlap@gmail.com',
    __v: 0
  }
]
total students number = 4

name is : Mayuk Mukherjee, email is : Mayuk@gmail.com
Student is currently living in state : California, at district is : Ohio, at city is : Colorado
Mayuk Mukherjee , has got total marks of = 277, average = 92.33,
 with a grade of : Excellent
Marks in physics = 97, chemistry = 84, mathematics = 96


name is : Suryendu Sarkar, email is : Suryendu@gmail.com
Student is currently living in state : Alabama, at district is : Denver, at city is : California
Suryendu Sarkar , has got total marks of = 207, average = 69.00,
 with a grade of : Good
Marks in physics = 61, chemistry = 76, mathematics = 70


name is : Aninda Mukherjee, email is : Aninda@gmail.com
Student is currently living in state : Alaska, at district is : Texas, at city is : Huston
Aninda Mukherjee , has got total marks of = 204, average = 68.00,
 with a grade of : Good
Marks in physics = 69, chemistry = 79, mathematics = 56


name is : Sanlap Gadai, email is : Sanlap@gmail.com
Student is currently living in state : MAssachuttes, at district is : Ohio, at city is : Atlanta
Sanlap Gadai , has got total marks of = 230, average = 76.67,
 with a grade of : Very Good
Marks in physics = 84, chemistry = 73, mathematics = 73

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
swapnanilwebdeveloper profile image
swapnanilWebDeveloper

If any one face any problem to understand this code , Please let me know your problem.
Comment me with the problem you face and let me help you clearing your concept