How do I build a dynamic query in Mongoose?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I need to build a query using the following sample data:



{
brandFilters:[ { brand: 'Amana', checked: true },
{ brand: 'Whirlpool', checked: true } ],
priceFilters:[ { low: 100, high: 200, label: '$100 - $200', checked: true },
{ low: 200, high: 300, label: '$200 - $300', checked: true } ],
rating: null }


The first segment of the query builds the brands criteria as shown here;



let brands = ;
let productQuery = Product.find();

if(filters.brandFilters.length) {
for(let filter of filters.brandFilters) {
brands.push(filter.brand)
}

productQuery.where('brand').in(brands)
console.log('brands', brands)
}


The second segment is supposed build the price criteria as shown here:



if(filters.priceFilters.length) {
for(let filter of filters.priceFilters) {
productQuery.where('price').gte(+filter.low).lte(+filter.high);
}
}


The intention is to add a "where" clause for each price filter as shown in the data above. The problem is multiple where clauses for the price criteria are not being added. Each successive price filter in the for loop overwrites the last. So instead of having multiple "where" clauses for my price filters, the query only contains one for the last iteration of the for loop.



I am trying to get to a query that would look like this:



productQuery.where('brand').in(['Amana', 'Whirlpool'])
productQuery.where('price').gte(100).lte(200)
productQuery.where('price').gte(200).lte(300)









share|improve this question























  • FWIW, I haven't seen many sites that allow a filter on multiple price ranges. The example you give for a thing you'd want should just be productQuery.where('price').gte(100).lte(300).

    – Paul
    Jan 4 at 19:02


















1















I need to build a query using the following sample data:



{
brandFilters:[ { brand: 'Amana', checked: true },
{ brand: 'Whirlpool', checked: true } ],
priceFilters:[ { low: 100, high: 200, label: '$100 - $200', checked: true },
{ low: 200, high: 300, label: '$200 - $300', checked: true } ],
rating: null }


The first segment of the query builds the brands criteria as shown here;



let brands = ;
let productQuery = Product.find();

if(filters.brandFilters.length) {
for(let filter of filters.brandFilters) {
brands.push(filter.brand)
}

productQuery.where('brand').in(brands)
console.log('brands', brands)
}


The second segment is supposed build the price criteria as shown here:



if(filters.priceFilters.length) {
for(let filter of filters.priceFilters) {
productQuery.where('price').gte(+filter.low).lte(+filter.high);
}
}


The intention is to add a "where" clause for each price filter as shown in the data above. The problem is multiple where clauses for the price criteria are not being added. Each successive price filter in the for loop overwrites the last. So instead of having multiple "where" clauses for my price filters, the query only contains one for the last iteration of the for loop.



I am trying to get to a query that would look like this:



productQuery.where('brand').in(['Amana', 'Whirlpool'])
productQuery.where('price').gte(100).lte(200)
productQuery.where('price').gte(200).lte(300)









share|improve this question























  • FWIW, I haven't seen many sites that allow a filter on multiple price ranges. The example you give for a thing you'd want should just be productQuery.where('price').gte(100).lte(300).

    – Paul
    Jan 4 at 19:02














1












1








1


1






I need to build a query using the following sample data:



{
brandFilters:[ { brand: 'Amana', checked: true },
{ brand: 'Whirlpool', checked: true } ],
priceFilters:[ { low: 100, high: 200, label: '$100 - $200', checked: true },
{ low: 200, high: 300, label: '$200 - $300', checked: true } ],
rating: null }


The first segment of the query builds the brands criteria as shown here;



let brands = ;
let productQuery = Product.find();

if(filters.brandFilters.length) {
for(let filter of filters.brandFilters) {
brands.push(filter.brand)
}

productQuery.where('brand').in(brands)
console.log('brands', brands)
}


The second segment is supposed build the price criteria as shown here:



if(filters.priceFilters.length) {
for(let filter of filters.priceFilters) {
productQuery.where('price').gte(+filter.low).lte(+filter.high);
}
}


The intention is to add a "where" clause for each price filter as shown in the data above. The problem is multiple where clauses for the price criteria are not being added. Each successive price filter in the for loop overwrites the last. So instead of having multiple "where" clauses for my price filters, the query only contains one for the last iteration of the for loop.



I am trying to get to a query that would look like this:



productQuery.where('brand').in(['Amana', 'Whirlpool'])
productQuery.where('price').gte(100).lte(200)
productQuery.where('price').gte(200).lte(300)









share|improve this question














I need to build a query using the following sample data:



{
brandFilters:[ { brand: 'Amana', checked: true },
{ brand: 'Whirlpool', checked: true } ],
priceFilters:[ { low: 100, high: 200, label: '$100 - $200', checked: true },
{ low: 200, high: 300, label: '$200 - $300', checked: true } ],
rating: null }


The first segment of the query builds the brands criteria as shown here;



let brands = ;
let productQuery = Product.find();

if(filters.brandFilters.length) {
for(let filter of filters.brandFilters) {
brands.push(filter.brand)
}

productQuery.where('brand').in(brands)
console.log('brands', brands)
}


The second segment is supposed build the price criteria as shown here:



if(filters.priceFilters.length) {
for(let filter of filters.priceFilters) {
productQuery.where('price').gte(+filter.low).lte(+filter.high);
}
}


The intention is to add a "where" clause for each price filter as shown in the data above. The problem is multiple where clauses for the price criteria are not being added. Each successive price filter in the for loop overwrites the last. So instead of having multiple "where" clauses for my price filters, the query only contains one for the last iteration of the for loop.



I am trying to get to a query that would look like this:



productQuery.where('brand').in(['Amana', 'Whirlpool'])
productQuery.where('price').gte(100).lte(200)
productQuery.where('price').gte(200).lte(300)






node.js mongodb mongoose






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 4 at 18:42









koquekoque

3831318




3831318













  • FWIW, I haven't seen many sites that allow a filter on multiple price ranges. The example you give for a thing you'd want should just be productQuery.where('price').gte(100).lte(300).

    – Paul
    Jan 4 at 19:02



















  • FWIW, I haven't seen many sites that allow a filter on multiple price ranges. The example you give for a thing you'd want should just be productQuery.where('price').gte(100).lte(300).

    – Paul
    Jan 4 at 19:02

















FWIW, I haven't seen many sites that allow a filter on multiple price ranges. The example you give for a thing you'd want should just be productQuery.where('price').gte(100).lte(300).

– Paul
Jan 4 at 19:02





FWIW, I haven't seen many sites that allow a filter on multiple price ranges. The example you give for a thing you'd want should just be productQuery.where('price').gte(100).lte(300).

– Paul
Jan 4 at 19:02












1 Answer
1






active

oldest

votes


















1














So the query you're trying to build should look like below:



{
"$and":[
{"$or":[
{"price":{"$gte":100,"$lte":200}},
{"price":{"$gte":200,"$lte":300}}
]
},
{"brand":{"$in":["Amana","Whirlpool"]}}
]
}


So it contains $or to include multiple price ranges. To do that you can build that query as plain JavaScript object and then pass it to find method, try:



let query = {
'$and':
};

var priceQuery = ;
let brands = ;

if(filters.priceFilters.length) {
for(let filter of filters.priceFilters) {
priceQuery.push({ 'price': { $gte: +filter.low, $lte: +filter.high } });
}

query['$and'].push({ '$or': priceQuery });
};

if(filters.brandFilters.length) {
for(let filter of filters.brandFilters) {
brands.push(filter.brand)
}

query['$and'].push({ 'brand': { '$in': brands } });
}


and then



let products = await Product.find(query);





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54044420%2fhow-do-i-build-a-dynamic-query-in-mongoose%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    So the query you're trying to build should look like below:



    {
    "$and":[
    {"$or":[
    {"price":{"$gte":100,"$lte":200}},
    {"price":{"$gte":200,"$lte":300}}
    ]
    },
    {"brand":{"$in":["Amana","Whirlpool"]}}
    ]
    }


    So it contains $or to include multiple price ranges. To do that you can build that query as plain JavaScript object and then pass it to find method, try:



    let query = {
    '$and':
    };

    var priceQuery = ;
    let brands = ;

    if(filters.priceFilters.length) {
    for(let filter of filters.priceFilters) {
    priceQuery.push({ 'price': { $gte: +filter.low, $lte: +filter.high } });
    }

    query['$and'].push({ '$or': priceQuery });
    };

    if(filters.brandFilters.length) {
    for(let filter of filters.brandFilters) {
    brands.push(filter.brand)
    }

    query['$and'].push({ 'brand': { '$in': brands } });
    }


    and then



    let products = await Product.find(query);





    share|improve this answer




























      1














      So the query you're trying to build should look like below:



      {
      "$and":[
      {"$or":[
      {"price":{"$gte":100,"$lte":200}},
      {"price":{"$gte":200,"$lte":300}}
      ]
      },
      {"brand":{"$in":["Amana","Whirlpool"]}}
      ]
      }


      So it contains $or to include multiple price ranges. To do that you can build that query as plain JavaScript object and then pass it to find method, try:



      let query = {
      '$and':
      };

      var priceQuery = ;
      let brands = ;

      if(filters.priceFilters.length) {
      for(let filter of filters.priceFilters) {
      priceQuery.push({ 'price': { $gte: +filter.low, $lte: +filter.high } });
      }

      query['$and'].push({ '$or': priceQuery });
      };

      if(filters.brandFilters.length) {
      for(let filter of filters.brandFilters) {
      brands.push(filter.brand)
      }

      query['$and'].push({ 'brand': { '$in': brands } });
      }


      and then



      let products = await Product.find(query);





      share|improve this answer


























        1












        1








        1







        So the query you're trying to build should look like below:



        {
        "$and":[
        {"$or":[
        {"price":{"$gte":100,"$lte":200}},
        {"price":{"$gte":200,"$lte":300}}
        ]
        },
        {"brand":{"$in":["Amana","Whirlpool"]}}
        ]
        }


        So it contains $or to include multiple price ranges. To do that you can build that query as plain JavaScript object and then pass it to find method, try:



        let query = {
        '$and':
        };

        var priceQuery = ;
        let brands = ;

        if(filters.priceFilters.length) {
        for(let filter of filters.priceFilters) {
        priceQuery.push({ 'price': { $gte: +filter.low, $lte: +filter.high } });
        }

        query['$and'].push({ '$or': priceQuery });
        };

        if(filters.brandFilters.length) {
        for(let filter of filters.brandFilters) {
        brands.push(filter.brand)
        }

        query['$and'].push({ 'brand': { '$in': brands } });
        }


        and then



        let products = await Product.find(query);





        share|improve this answer













        So the query you're trying to build should look like below:



        {
        "$and":[
        {"$or":[
        {"price":{"$gte":100,"$lte":200}},
        {"price":{"$gte":200,"$lte":300}}
        ]
        },
        {"brand":{"$in":["Amana","Whirlpool"]}}
        ]
        }


        So it contains $or to include multiple price ranges. To do that you can build that query as plain JavaScript object and then pass it to find method, try:



        let query = {
        '$and':
        };

        var priceQuery = ;
        let brands = ;

        if(filters.priceFilters.length) {
        for(let filter of filters.priceFilters) {
        priceQuery.push({ 'price': { $gte: +filter.low, $lte: +filter.high } });
        }

        query['$and'].push({ '$or': priceQuery });
        };

        if(filters.brandFilters.length) {
        for(let filter of filters.brandFilters) {
        brands.push(filter.brand)
        }

        query['$and'].push({ 'brand': { '$in': brands } });
        }


        and then



        let products = await Product.find(query);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 4 at 19:12









        micklmickl

        16.4k61841




        16.4k61841
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54044420%2fhow-do-i-build-a-dynamic-query-in-mongoose%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            generate and download xml file after input submit (php and mysql) - JPK

            Angular Downloading a file using contenturl with Basic Authentication

            Can't read property showImagePicker of undefined in react native iOS