Conditional where clause in firestore queries

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.


Solution 1:

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()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.data())
      })
    })
    .catch(catchError)
}