Mongoose QueryBuilder inside and outside schema with[ find, where, gt, lt, gte, lte, equals] different queries # Diffuclty Hard
Tags: javascript, webdev, programming, database
Published: 2024-02-08 16:49:39

###here is the code for query builder in mongoose .
###QueryBuiders are very important in mongoose because you can build queries inside QueryBuilders and define any type of query as per your requirement.
### You can call these querybuilders multiple times as much you need it . But if you do not create your own query builder then you have to write that query each time whenever you need that query.
### QueryBuilder helps you to write efficient code and make your program better


```Javascript
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,
             price : Number,
             discPerc : Number,
             discAvailable : Boolean,
             CountryOrigin : String,
        },
        {
          query: {
            // findByName query is here
            async byName(name) {
              console.log("Out of query builder function()....");

              const resAnimal = await this.where("name").equals(name);
              console.log("all the animals of name = "+name+" is found "+resAnimal.length);
              console.log(resAnimal);

              for(var i = 0; i < resAnimal.length; i++){
                    console.log("name of the animaal = "+resAnimal[i].name);
                    console.log("breed of the animaal = "+resAnimal[i].breed);
                    console.log("price of the animaal = "+resAnimal[i].price);
                    console.log("discPerc of the animaal = "+resAnimal[i].discPerc);
                    console.log("discAvailable of the animaal = "+resAnimal[i].discAvailable);
                    console.log("CountryOrigin of the animaal = "+resAnimal[i].CountryOrigin);
              }

              return resAnimal;
            },

           // findByPrice query is here

           async byPrice(min, max) {
            console.log("Out of query builder function()....");
            
            //await Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec();

            const resAnimal = await this.where("price").gte(min).lte(max);
            console.log("all the animals of price between = $"+min+" and $"+max+" is found "+resAnimal.length);
            console.log(resAnimal);

            for(var i = 0; i < resAnimal.length; i++){
                  console.log("name of the animal = "+resAnimal[i].name);
                  console.log("breed of the animal = "+resAnimal[i].breed);
                  console.log("price of the animal = "+resAnimal[i].price);
                  console.log("discPerc of the animal = "+resAnimal[i].discPerc);
                  console.log("discAvailable of the animal = "+resAnimal[i].discAvailable);
                  console.log("CountryOrigin of the animal = "+resAnimal[i].CountryOrigin);

                  if(resAnimal[i].discAvailable){
                    const netPrice = resAnimal[i].price -  resAnimal[i].price * (resAnimal[i].discPerc / 100);
                    console.log("\nprice after discount = $"+netPrice);
                  }
                  else{
                    console.log("\nDiscount is not available...for : "+resAnimal[i].name);
                  }
            }

            return resAnimal;
          }, 

          }
        });

        animalSchema.query.byBreed = async function(animal_breed) {
            console.log("byBreed function is executing...");

            const resAnimal = await this.where('breed').equals(animal_breed);
            console.log("all the breed of : "+animal_breed+", found = "+resAnimal.length+" times..");

            for(var i = 0; i < resAnimal.length; i++){
                console.log("\nname of the animal : "+resAnimal[i].name);
                console.log("breed of the animal : "+resAnimal[i].breed);
                console.log("price of the animal : $"+resAnimal[i].price);
                console.log("discPerc of the animal : "+resAnimal[i].discPerc+" '%' ");
                console.log("discAvailable of the animal : "+resAnimal[i].discAvailable);
                console.log("CountryOrigin of the animal : "+resAnimal[i].CountryOrigin);
            }

            return resAnimal;
          };

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

        await  Animal.insertMany([
            { 
               name: "Agean",
               breed: "Cat",
               price : 240,
               discPerc : 16,
               discAvailable : true,
               CountryOrigin : "Greece",
            },
            { 
                name: "American Bobtail",
                breed: "Cat",
                price : 355,
                discPerc : 23,
                discAvailable : true,
                CountryOrigin : "United States",
             },
             { 
                name: "Common KeelBack",
                breed: "Snake",
                price : 157,
                discPerc : 34,
                discAvailable : false,
                CountryOrigin : "New Guinea",
             },
             { 
                name: "Glosy Snake",
                breed: "Snake",
                price : 497,
                discPerc : 29,
                discAvailable : false,
                CountryOrigin : "Mexico",
             },
             { 
                name: "Philippine forest rat",
                breed: "Rat",
                price : 179,
                discPerc : 7,
                discAvailable : true,
                CountryOrigin : "Philippines",
             },
             { 
                name: "Rare UniBack",
                breed: "Rat",
                price : 88,
                discPerc : 13,
                discAvailable : false,
                CountryOrigin : "New Guinea",
             },
        ]);

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

          const nameResult = await Animal.find().byName('Glosy Snake');
          console.log(nameResult);
   
         const breedResult = await Animal.find().byBreed("Rat");
         console.log(breedResult);  
      
         const priceResult = await Animal.find().byPrice(100, 200);
         console.log(priceResult);   
}

```

Here we have created byName(), byPrice(), byBreed() these three query builder . Among these three queryBuilders only one is outside the schema , i.e : byBreed() . byName() and byPrice() are built inside schema . Now checkout the output : 

```Javascript

PS C:\Users\USER\Downloads\mongoExpress\SchemaModel_QueryBuilders> node src/queryBuilder_1.js
[
  {
    _id: new ObjectId('65c4fdcc73ad7f090cd8cd0d'),
    name: 'Siberian Husky',
    breed: 'Dog',
    countryOrigin: 'Siberia',
    __v: 0
  },
  {
    _id: new ObjectId('65c4fdcc73ad7f090cd8cd0e'),
    name: 'British Smooth Hair',
    breed: 'Cat',
    countryOrigin: 'United Kingdom',
    __v: 0
  },
  {
    _id: new ObjectId('65c4fdcc73ad7f090cd8cd0f'),
    name: 'American Short Hair',
    breed: 'Cat',
    countryOrigin: 'USA',
    __v: 0
  },
  {
    _id: new ObjectId('65c4fdcc73ad7f090cd8cd10'),
    name: 'Bull Dog',
    breed: 'Dog',
    countryOrigin: 'Switzerland',
    __v: 0
  },
  {
    _id: new ObjectId('65c500ee9a015a02983f3dd9'),
    name: 'Agean',
    breed: 'Cat',
    price: 240,
    discPerc: 16,
    discAvailable: true,
    CountryOrigin: 'Greece',
    __v: 0
  },
  {
    _id: new ObjectId('65c500ee9a015a02983f3dda'),
    name: 'American Bobtail',
    breed: 'Cat',
    price: 355,
    discPerc: 23,
    discAvailable: true,
    CountryOrigin: 'United States',
    __v: 0
  },
  {
    _id: new ObjectId('65c500ee9a015a02983f3ddb'),
    name: 'Common KeelBack',
    breed: 'Snake',
    price: 157,
    discPerc: 34,
    discAvailable: false,
    CountryOrigin: 'New Guinea',
    __v: 0
  },
  {
    _id: new ObjectId('65c500ee9a015a02983f3ddc'),
    name: 'Glosy Snake',
    breed: 'Snake',
    price: 497,
    discPerc: 29,
    discAvailable: false,
    CountryOrigin: 'Mexico',
    __v: 0
  },
  {
    _id: new ObjectId('65c500ee9a015a02983f3ddd'),
    name: 'Philippine forest rat',
    breed: 'Rat',
    price: 179,
    discPerc: 7,
    discAvailable: true,
    CountryOrigin: 'Philippines',
    __v: 0
  },
  {
    _id: new ObjectId('65c500ee9a015a02983f3dde'),
    name: 'Rare UniBack',
    breed: 'Rat',
    price: 88,
    discPerc: 13,
    discAvailable: false,
    CountryOrigin: 'New Guinea',
    __v: 0
  }
]
Out of query builder function()....
all the animals of name = Glosy Snake is found 1
[
  {
    _id: new ObjectId('65c500ee9a015a02983f3ddc'),
    name: 'Glosy Snake',
    breed: 'Snake',
    price: 497,
    discPerc: 29,
    discAvailable: false,
    CountryOrigin: 'Mexico',
    __v: 0
  }
]
name of the animaal = Glosy Snake
breed of the animaal = Snake
price of the animaal = 497
discPerc of the animaal = 29
discAvailable of the animaal = false
CountryOrigin of the animaal = Mexico
[
  {
    _id: new ObjectId('65c500ee9a015a02983f3ddc'),
    name: 'Glosy Snake',
    breed: 'Snake',
    price: 497,
    discPerc: 29,
    discAvailable: false,
    CountryOrigin: 'Mexico',
    __v: 0
  }
]
byBreed function is executing...
all the breed of : Rat, found = 2 times..

name of the animal : Philippine forest rat
breed of the animal : Rat
price of the animal : $179
discPerc of the animal : 7 '%'
discAvailable of the animal : true
CountryOrigin of the animal : Philippines

name of the animal : Rare UniBack
breed of the animal : Rat
price of the animal : $88
discPerc of the animal : 13 '%'
discAvailable of the animal : false
CountryOrigin of the animal : New Guinea
[
  {
    _id: new ObjectId('65c500ee9a015a02983f3ddd'),
    name: 'Philippine forest rat',
    breed: 'Rat',
    price: 179,
    discPerc: 7,
    discAvailable: true,
    CountryOrigin: 'Philippines',
    __v: 0
  },
  {
    _id: new ObjectId('65c500ee9a015a02983f3dde'),
    name: 'Rare UniBack',
    breed: 'Rat',
    price: 88,
    discPerc: 13,
    discAvailable: false,
    CountryOrigin: 'New Guinea',
    __v: 0
  }
]
Out of query builder function()....
all the animals of price between = $100 and $200 is found 2
[
  {
    _id: new ObjectId('65c500ee9a015a02983f3ddb'),
    name: 'Common KeelBack',
    breed: 'Snake',
    price: 157,
    discPerc: 34,
    discAvailable: false,
    CountryOrigin: 'New Guinea',
    __v: 0
  },
  {
    _id: new ObjectId('65c500ee9a015a02983f3ddd'),
    name: 'Philippine forest rat',
    breed: 'Rat',
    price: 179,
    discPerc: 7,
    discAvailable: true,
    CountryOrigin: 'Philippines',
    __v: 0
  }
]
name of the animal = Common KeelBack
breed of the animal = Snake
price of the animal = 157
discPerc of the animal = 34
discAvailable of the animal = false
CountryOrigin of the animal = New Guinea

Discount is not available...for : Common KeelBack
name of the animal = Philippine forest rat
breed of the animal = Rat
price of the animal = 179
discPerc of the animal = 7
discAvailable of the animal = true
CountryOrigin of the animal = Philippines

price after discount = $166.47
[
  {
    _id: new ObjectId('65c500ee9a015a02983f3ddb'),
    name: 'Common KeelBack',
    breed: 'Snake',
    price: 157,
    discPerc: 34,
    discAvailable: false,
    CountryOrigin: 'New Guinea',
    __v: 0
  },
  {
    _id: new ObjectId('65c500ee9a015a02983f3ddd'),
    name: 'Philippine forest rat',
    breed: 'Rat',
    price: 179,
    discPerc: 7,
    discAvailable: true,
    CountryOrigin: 'Philippines',
    __v: 0
  }
]

```