Firestore: Multiple conditional where clauses

rendom picture rendom · Dec 30, 2017 · Viewed 22.2k times · Source

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 => {...

Answer

Doug Stevenson picture Doug Stevenson · Dec 30, 2017

As you can see in the API docs, the collection() method returns a CollectionReference. CollectionReference extends Query. Query.where() and Query.orderBy() also return Query objects. 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(...)
}