0

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();
4
  • What errors do you get on running this code? Commented Jan 4, 2022 at 19:09
  • I have no error on output, it looks like .where() isn't attached to query Commented Jan 4, 2022 at 19:22
  • Can you try changing the last line to const snapshot = await query.get() instead of assigning the result to query itself. I would also log filterParams to check if all values are as intended Commented Jan 4, 2022 at 19:23
  • filterParams has been checked, I changed const snapshot = await query.get() but it doesn't work. Commented Jan 4, 2022 at 20:46

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.