10

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
  • 73,993
  • 25
  • 133
  • 124
asanas
  • 3,212
  • 8
  • 34
  • 61

1 Answers1

34

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)
}
Doug Stevenson
  • 268,359
  • 30
  • 341
  • 380
  • 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
  • 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