15

I have fetch some data from firestore but in my query I want to add a conditional where clause. I am using async-await for api and not sure how to add a consitional where clause.

Here is my function

export async function getMyPosts (type) {
  await api
  var myPosts = []

  const posts = await api.firestore().collection('posts').where('status', '==', 'published')
    .get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.data())
      })
    })
    .catch(catchError)
}

In my main function I am getting a param called 'type'. Based on the value of that param I want to add another qhere clause to the above query. For example, if type = 'nocomments', then I want to add a where clause .where('commentCount', '==', 0), otherwise if type = 'nocategories', then the where clause will be querying another property like .where('tags', '==', 'none')

I am unable to understand how to add this conditional where clause.

NOTE: in firestore you add multiple conditions by just appending your where clauses like - .where("state", "==", "CA").where("population", ">", 1000000) and so on.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
asanas
  • 3,782
  • 11
  • 43
  • 72

2 Answers2

41

Add the where clause to the query only when needed:

export async function getMyPosts (type) {
  await api
  var myPosts = []

  var query = api.firestore().collection('posts')
  if (your_condition_is_true) {  // you decide
    query = query.where('status', '==', 'published')
  }
  const questions = await query.get()
}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 1
    How to query = query.doc(myId) dynamically? I've tried with this example and works with **where** clause but not with **doc**. – Jonathan Arias Jun 27 '19 at 15:25
  • 1
    is this still valid in new firestore? the collection, does it have a "where" method or is it through "ref" parent object? – Ayyash Jun 14 '21 at 09:06
  • Hi, what is "api", from where it can be imported ? I see query starting like this - const store = admin.firestore();....Is your api same as my admin ? – Kris Swat Jun 13 '23 at 17:40
0

For the frontend Web SDK:

Or you can look at this link for a different method: Firestore conditional where clause using Modular SDK v9

let showPublishStatus: boolean = true

let conditionalConstraint: QueryConstraint = showPublishStatus 
? where("status", "==", "published") 
: where("status", "!=", "published")

let queryWebSDK = query(collection(db, "Collection"), conditionalConstraint)