Adam Szymański
Adam Szymański

Reputation: 365

How to add query operators to query of Firestore?

I have problem. My app allows user to filter offers by few params. I would like to fetch data with .where() operator by I need to stack them. How can I do it?

My attempt (don't work):

let query = db.collection("cards").where("cardId", "==", id);

  if (filterParams.price.from && filterParams.price.to) {
    query
      .where("price", ">=", filterParams.price.from)
      .where("price", "<=", filterParams.price.to);
  }
  if (filterParams.graded) {
    query.where("isGraded", "==", filterParams.graded);
  }
  if (filterParams.condition) {
    query.where("condition", "==", filterParams.condition);
  }

  query = await query.get();

Upvotes: 0

Views: 47

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

Query objects are immutable. Each time you call where it returns a new Query object, which you need to then keep a reference to that query.

So:

let query = db.collection("cards").where("cardId", "==", id);

if (filterParams.price.from && filterParams.price.to) {
  query = query // 👈
    .where("price", ">=", filterParams.price.from)
    .where("price", "<=", filterParams.price.to);
}
if (filterParams.graded) {
  query = query.where("isGraded", "==", filterParams.graded); // 👈
}
if (filterParams.condition) {
  query = query.where("condition", "==", filterParams.condition); // 👈
}

query = await query.get();

Upvotes: 2

Related Questions