Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 => {...
like image 693
rendom Avatar asked Dec 30 '17 18:12

rendom


2 Answers

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(...)
}
like image 181
Doug Stevenson Avatar answered Nov 12 '22 15:11

Doug Stevenson


Firebase Version 9

The docs do not cover this but here is how to add conditional where clauses to a query

import { collection, query, where } from 'firebase/firestore'

const queryConstraints = []
if (group != null) queryConstraints.push(where('group', '==', group))
if (pro != null) queryConstraints.push(where('pro', '==', pro))
const q = query(collection(db, 'videos'), ...queryConstraints)

The source of this answer is a bit of intuitive guesswork and help from my best friend J-E^S^-U-S

like image 20
danday74 Avatar answered Nov 12 '22 14:11

danday74