skip to Main Content

I am trying to add dynamic conditions on firebase query. But somehow not working. I also try chatgpt but that is also not provide me the best solution. Please help me to fix my issue.

Type ‘CollectionReference’ is not assignable to type ‘Query’.

enter image description here


getListing(): Observable<Listing[]> {
    return this.afs
      .collection<Listing>('listing', (ref) => {
        let query: firebase.firestore.Query =ref;
        for (const [key, value] of Object.entries(this.searchFilter)) {
         query= query.where(key, "==", value)
        }
        return ref.orderBy('createdAt', 'asc')
      })
      .snapshotChanges()
      .pipe(
        map((actions) =>
          actions.map((action) => {
            const id = action.payload.doc.id;
            const data = action.payload.doc.data() as Listing;
            return { id, ...data } as Listing;
          })
        )
      );
  }

Any solution appreciated!

2

Answers


  1. Chosen as BEST ANSWER

    After lot of struggle. Finally i am able to solve the issue by my own.

    getListing(filter: Filter | undefined = undefined): Observable<Listing[]> {
        return new Observable((observer) => {
          let collectionRef = this.afs.collection<Listing>('listing').ref;
          let query = collectionRef.orderBy('createdAt', 'asc');
          if (filter) {
            for (const [key, value] of Object.entries(filter)) {
              query = query.where(key, "==", value)
            }
          }
          query.get().then((querySnapshot) => {
            const data: Listing[] = [];
            querySnapshot.forEach((doc) => {
              const id = doc.id;
              const listing = doc.data() as Listing;
              data.push({ id, ...listing });
            });
            observer.next(data);
            observer.complete();
          });
        });
      }
    
    

  2. As follow this example in GitHub by defining query as firebase.firestore.CollectionReference | firebase.firestore.Query type should be able to resolve the issue.

    let query: firebase.firestore.CollectionReference | firebase.firestore.Query = ref;
    
    for (const [key, value] of Object.entries(this.searchFilter)) {
      query = query.where(key, "==", value)
    }
    
    return query.orderBy('createdAt', 'asc');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search