Hi all,
I’m currently struggling to build search queries to find ‘vehicles’ in my database.
I need to be able to search using multiple parameters at once, however the input can contain null or empty values.
At the frontend, the user submits a search form, creating an object that might look like this:
{
“make”: “Nissan”,
“model”: null,
“year”: "2001
}
I want the query to disregard the null field and search for all vehicles based on make = "Nissan’ AND year = ‘2001’.
If I use lots of ‘and()’ calls the query will return nothing as the null field is taken into consideration.
Is there any way to do this relatively efficiently without having to code for every possible combination?
Here’s my frontend code (so far) for reference:
import {vehicleSearch} from 'backend/vehicleServices';
$w.onReady(function () {
//TODO: write your page related code here...
let vehicle = {
"make": "Nissan",
"model": null,
"year": "2001"
}
vehicleSearch(vehicle).then(result => {
console.log(result);
});
});
And my backend code (I know it’s is wrong but it should give you a better idea of what I’m trying to do):
export function vehicleSearch(vehicle) {
if (vehicle.make === '' ||vehicle.make === null) {
let makeQuery = wixData.query("vehicle").contains("make", vehicle.make);
}
if (vehicle.model === '' ||vehicle.model === null) {
let modelQuery = wixData.query("vehicle").contains("model", vehicle.model);
}
if (vehicle.year === '' ||vehicle.year === null) {
let yearQuery = wixData.query("vehicle").eq("year", vehicle.year);
}
return makeQuery.and(modelQuery).and(yearQuery).find().then((results) => {
return results.items;
});
}
Any ideas would be much, much appreciated.
Thanks,
Alvi