How to do advance filter and sort ( E-commerce ) using Firestore

牧云@^-^@ 提交于 2021-02-05 11:26:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!