问题
I am trying to build an E-commerce app using firebase firestore, i am stuck at filtering and and sorting the product on user input. I am able to apply all filter and sort but I want to do the filter on user input and i cannot leave the where clause empty
so i want to generate a fire base query on user input without so if or leave the where clause empty so it doesn't effect the query
how can i generate the query dynamically
.collection('allProducts')
.where('published', '==', true)
.where('category', 'array-contains-any', keyword)
.where('color', '==', colorSelected)
.orderBy('price')
.where('price', '>', priceRange[0])
.where('price', '<', priceRange[1])
.orderBy('createdAt', 'desc');```
回答1:
Cloud Firestore queries are immutable. If you try to change the value by calling for example:
.where('color', '==', colorSelected)
Your query simply becomes a new query. To solve this, you have to create a reference to the allProducts collection and then add a new filter, according to what the user has selected. This is an example:
const db = firebase.firestore();
const allProductsRef = db.collection("allProducts");
const basicQuery;
if(userHasSelectedColor) {
basicQuery = allProductsRef.where('color', '==', colorSelected);
} else if (userHasSelectedColorAndCategory) {
basicQuery = allProductsRef.where('color', '==', colorSelected)
.where('category', 'array-contains-any', keyword);
}
In this way, you can chain as many function calls as you need.
来源:https://stackoverflow.com/questions/60624654/how-to-do-advance-filter-and-sort-e-commerce-using-firestore