Skip to content
Advertisement

Firestore: Multiple conditional where clauses

For example I have dynamic filter for my list of books where I can set specific color, authors and categories. This filter can set multiple colors at once and multiple categories.

   Book > Red, Blue > Adventure, Detective.

How can I add “where” conditionally?

  firebase
    .firestore()
    .collection("book")
    .where("category", "==", )
    .where("color", "==", )
    .where("author", "==", )

    .orderBy("date")
    .get()
    .then(querySnapshot => {...

Advertisement

Answer

As you can see in the API docs, the collection() method returns a CollectionReference. CollectionReference extends Query, and Query objects are immutable. Query.where() and Query.orderBy() return new Query objects that add operations on top of the original Query (which remains unmodified). You will have to write code to remember these new Query objects so you can continue to chain calls with them. So, you can rewrite your code like this:

var query = firebase.firestore().collection("book")
query = query.where(...)
query = query.where(...)
query = query.where(...)
query = query.orderBy(...)
query.get().then(...)

Now you can put in conditionals to figure out which filters you want to apply at each stage. Just reassign query with each newly added filter.

if (some_condition) {
    query = query.where(...)
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement