Querying a single database with multiple variables

Hi,

I has 11 filter variables to use for a database query. I need some way of selecting which variables to query based on which ones have been filled out with text.

I.e if (variable1.value !== “” && variable 2.value === “”) but for all combinations of the 11 variables.

Any ideas on how to do this without creating like 100+ if statements for each query case?

Thanks!

import wixData form 'wix-data';
wixData.query("CollectionName")
.isNotEmpty('fieldKey1')
.isNotEmpty('fieldKey2')
.limit(1000)
.find()
.then(res => {
    if (res.items.length > 0){
        //continue from here
    }
})

Or:

import wixData form 'wix-data';
const fields = ["name", "address", "nickname"];
let query = wixData.query("CollectionName");
fields.forEach(e => query = query.isNotEmpty(e));
query.limit(1000).find()
.then(res => {
    if (res.items.length > 0){
        //continue from here
    }
    })

@jonatandor35 Thanks for this. One quick question… how do I use the “e” constructor to include all of the search variables?

@anneynorton7 Please elaborate. What exactly you’re trying to do.

@jonatandor35 I want it to check all 11 inputs to see if they have a value or not and then query from 4 different fields
ie see if $w(‘#name’).value !== “”, $w(‘#rating1’).value !== “”, $w(‘#rating2’).value !== “”
and then query $w(‘#name’).value from field “name”
and query $w(‘#rating1’).value and $w(‘#rating2’).value from field “rating” in a compact way.

You help haas been amazing btw. Thank you!

@anneynorton7 you should decide when you want to check it (onChange? On another occasion).
Set all the inputs as “required”
Then:

let inputs = [$w("#input1"), $w("#input2"), $w("#input3")];
let fields = ["name", "rating1", "rating2" ]//keep the order of the inputs
if (inputs.every(e => e.valid)){
    let query = wixData.query("CollectionName");
    fields.forEach((e, index) => query = query.eq(e, inputs[index].value));
    query.limit(1000).find()
    .then(res => {
        if (res.items.length > 0){
            //continue from here
        }
    })
})

Great! I will try it out and let you know. Thanks for all of the help!!