Search code examples
angularfirebasegoogle-cloud-firestoreangularfire

Firebase multiple where queries in Angular


I want to filter data that comes from Firebase using where queries in Angular. But filter only works when I enter both values. But I want filter to work also when there are only one value how can I do it?

getRequest(id, data) {
    console.log(data);
    return this.firestore
      .collection('customers')
      .doc(id)
      .collection('requests', (x) =>
        x
          .where('trace_id', '==', data.traceID)
          .where('status', '==', +data.status)
      )
      .snapshotChanges();
  }

Solution

  • The callback to the collection method is a normal method, so you can use normal JavaScript constructs to get what you want. For example:

    .collection('requests', (x) => {
      let result: Query<DocumentData> = x;
      if (data.traceID) result = result.where('trace_id', '==', data.traceID);
      if (data.status)  result = result.where('status', '==', +data.status);
      return result;
    )