12

How to perform a query with conditional where() clause using Firebase Modular SDK (v9)?

Example query in name-spaced version (v8):

const status = "live"
const publishedAfter = 1630607348811

let q = firebase.firestore().collection("articles")

// filters selected by users
if (status) q = q.where("status", "==", "live")
if (publishedAfter) q = q.where("publishedAt", ">", publishedAfter)

const qSnapshot = await q.get()
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84

1 Answers1

33

Option 1: Conditionally adding QueryConstraint using previous as base

let q = query(collection(firestore, "articles"))

// filters selected by users
if (status) q = query(q, where("status", "==", "live"))
if (publishedAfter) q = query(q, where("publishedAt", ">", publishedAfter))

const qSnapshot = await getDocs(q);

Option 2: Conditionally adding QueryConstraints to an array

const constraints = []

// filters selected by users
if (status) constraints.push(where("status", "==", "live"))
if (publishedAfter) constraints.push(where("publishedAt", ">", publishedAfter))

const q = query(collection(firestore, "articles"), ...constraints)

const qSnapshot = await getDocs(q);
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • 3
    Unbelievable. After 2 days cracking my skull with this and all I had to do was deconstruct the array... Thank you. – Giovanni Di Toro Sep 19 '21 at 03:55
  • May I ask you to have a look at a Firebase related question here - https://stackoverflow.com/questions/73953421/firebase-javascript-shows-errors-if-used-outside-the-head-tag? – Istiaque Ahmed Oct 04 '22 at 22:21