DEV Community

Cover image for Mongoose Statics-Methods : Build statics-method inside and outside the Schema#Challange
swapnanilWebDeveloper
swapnanilWebDeveloper

Posted on

Mongoose Statics-Methods : Build statics-method inside and outside the Schema#Challange

I am giving a code for how to build statics methods inside and outside the Schema.

Statics methods are kind of similar to instance methods .

Let's check out some new concepts of mongoose

// getting-started.js
const mongoose = require('mongoose');

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

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

  const animalSchema = new mongoose.Schema({ name: String, breed: String, countryOrigin : String },
    {
      statics: {
        async findByBreed(animal_breed) {

           const species = await this.find({ breed: new RegExp(animal_breed) });
           console.log("All animal species is = "+species);

           console.log("all the breed = "+animal_breed+", total found animal number = "+species.length);

           for(var i = 0; i < species.length; i++){
            console.log("name is = "+species[i].name);
            console.log("breed is = "+species[i].breed);
            console.log("countryOrigin is = "+species[i].countryOrigin+"\n");
           }

           return species;
        }
      }
    });

    animalSchema.statics.findByName =  async function(animal_name, modelName) {

        console.log("I am inside findByName() method...."+animal_name);
        const nameAnimal = await modelName.find({ name: new RegExp(animal_name) });

        console.log(nameAnimal);
        console.log("number of animals with name : "+animal_name+" : found = "+nameAnimal.length);

        for(var i = 0; i < nameAnimal.length; i++){
             console.log("name of the animal = "+nameAnimal[i].name);
             console.log("breed of the animal = "+nameAnimal[i].breed);
             console.log("country of origin of the animal = "+nameAnimal[i].countryOrigin);
        }

        return nameAnimal;
      };

    const Animal = mongoose.model('Animal', animalSchema);

    await Animal.insertMany([
        { 
          name: 'Siberian Husky',
          breed : "Dog",
          countryOrigin : "Siberia"
        },
        { 
            name: 'British Smooth Hair',
            breed : "Cat",
            countryOrigin : "United Kingdom"
        },
        { 
            name: 'American Short Hair',
            breed : "Cat",
            countryOrigin : "USA"
        },
        { 
            name: 'Bull Dog',
            breed : "Dog",
            countryOrigin : "Switzerland"
        }
    ]);

    let animals = await Animal.find({});
    console.log(animals);

    const breedResult = await Animal.findByBreed("Dog", "Bull Dog");
    console.log(breedResult);

    const nameResult = await Animal.findByName("American Short Hair", Animal);
    console.log(nameResult);

}

Enter fullscreen mode Exit fullscreen mode

1)Here we have created a schema called animalSchema and a model regarding this called Animal .
2) Then we have built a statics method called "findByBreed"
inside the Schema and another one is "findByName" outside schema
3) Now check the output inside the terminal.

PS C:\Users\USER\Downloads\mongoExpress\SchemaModel_statics> node src/statics_1.js
[
  {
    _id: new ObjectId('65c4f4509bdd71e1a036333b'),
    name: 'German Shepard',
    type: 'Dog',
    priceUSD: 2500,
    discPerc: 22,
    discAvailable: true,
    countryOrigin: 'Germany',
    breedQuality: 'High',
    medicalExp: 490,
    __v: 0
  },
  {
    _id: new ObjectId('65c4f4509bdd71e1a036333c'),
    name: 'Husky',
    type: 'Dog',
    priceUSD: 1865,
    discPerc: 16,
    discAvailable: true,
    countryOrigin: 'Alaska',
    breedQuality: 'Medium',
    medicalExp: 255,
    __v: 0
  },
  {
    _id: new ObjectId('65c4f4509bdd71e1a036333d'),
    name: 'British Short Hair',
    type: 'Cat',
    priceUSD: 1250,
    discPerc: 34,
    discAvailable: false,
    countryOrigin: 'United Kingdom',
    breedQuality: 'Medium',
    medicalExp: 345,
    __v: 0
  },
  {
    _id: new ObjectId('65c4f4509bdd71e1a036333e'),
    name: 'American Fluffy',
    type: 'Cat',
    priceUSD: 1750,
    discPerc: 28,
    discAvailable: true,
    countryOrigin: 'United Kingdom',
    breedQuality: 'Low',
    medicalExp: 259,
    __v: 0
  },
  {
    _id: new ObjectId('65c4f4509bdd71e1a036333f'),
    name: 'Bittle Sumdohg',
    type: 'Rat',
    priceUSD: 2445,
    discPerc: 11,
    discAvailable: false,
    countryOrigin: 'Alaska',
    breedQuality: 'High',
    medicalExp: 735,
    __v: 0
  },
  {
    _id: new ObjectId('65c4f4509bdd71e1a0363340'),
    name: 'Rattle Snake',
    type: 'Snake',
    priceUSD: 3775,
    discPerc: 25,
    discAvailable: true,
    countryOrigin: 'Germany',
    breedQuality: 'Low',
    medicalExp: 1325,
    __v: 0
  },
  {
    _id: new ObjectId('65c4f4509bdd71e1a0363341'),
    name: 'Black Mamba',
    type: 'Snake',
    priceUSD: 1985,
    discPerc: 39,
    discAvailable: false,
    countryOrigin: 'Uited States of America',
    breedQuality: 'Medium',
    medicalExp: 688,
    __v: 0
  },
  {
    _id: new ObjectId('65c4fd3acb91cae32f906537'),
    name: 'Siberian Husky',
    breed: 'Dog',
    countryOrigin: 'Siberia',
    __v: 0
  },
  {
    _id: new ObjectId('65c4fd3acb91cae32f906538'),
    name: 'British Smooth Hair',
    breed: 'Cat',
    countryOrigin: 'United Kingdom',
    __v: 0
  },
  {
    _id: new ObjectId('65c4fd3acb91cae32f906539'),
    name: 'American Short Hair',
    breed: 'Cat',
    countryOrigin: 'USA',
    __v: 0
  },
  {
    _id: new ObjectId('65c4fd3acb91cae32f90653a'),
    name: 'Bull Dog',
    breed: 'Dog',
    countryOrigin: 'Switzerland',
    __v: 0
  }
]
All animal species is = {
  _id: new ObjectId('65c4fd3acb91cae32f906537'),
  name: 'Siberian Husky',
  breed: 'Dog',
  countryOrigin: 'Siberia',
  __v: 0
},{
  _id: new ObjectId('65c4fd3acb91cae32f90653a'),
  name: 'Bull Dog',
  breed: 'Dog',
  countryOrigin: 'Switzerland',
  __v: 0
}
all the breed = Dog, total found animal number = 2
name is = Siberian Husky
breed is = Dog
countryOrigin is = Siberia

name is = Bull Dog
breed is = Dog
countryOrigin is = Switzerland

[
  {
    _id: new ObjectId('65c4fd3acb91cae32f906537'),
    name: 'Siberian Husky',
    breed: 'Dog',
    countryOrigin: 'Siberia',
    __v: 0
  },
  {
    _id: new ObjectId('65c4fd3acb91cae32f90653a'),
    name: 'Bull Dog',
    breed: 'Dog',
    countryOrigin: 'Switzerland',
    __v: 0
  }
]
I am inside findByName() method....American Short Hair
[
  {
    _id: new ObjectId('65c4fd3acb91cae32f906539'),
    name: 'American Short Hair',
    breed: 'Cat',
    countryOrigin: 'USA',
    __v: 0
  }
]
number of animals with name : American Short Hair : found = 1
name of the animal = American Short Hair
breed of the animal = Cat
country of origin of the animal = USA
[
  {
    _id: new ObjectId('65c4fd3acb91cae32f906539'),
    name: 'American Short Hair',
    breed: 'Cat',
    countryOrigin: 'USA',
    __v: 0
  }

Enter fullscreen mode Exit fullscreen mode

MongoDBCompass output =>

output in MongoDBCompass

Top comments (1)

Collapse
 
swapnanilwebdeveloper profile image
swapnanilWebDeveloper

any problem in statics method just drop a comment at this post and let me know that you need a simple explanation.