Search code examples
angulartypescriptfirebasegoogle-cloud-firestoreangularfire2

Cannot use the "not equal" operator when querying for a collection in AngularFire


I am trying to pull a collection from Firebase that is not associated to the user. So far, I've successfully queried for the user's collection, but I can't seem to get the collection that is not associated with the user using the != operator.

Here's my code:

  // Does not work!
  eventCollection: AngularFirestoreCollection<Event> = this.angularFirestore.collection("events", ref =>
    ref.where("uid", "!=", this.firebaseAuth.auth.currentUser.uid)
  );
  eventCollection$: Observable<Event[]> = this.eventCollection.valueChanges();

  // Works!
  myCollection: AngularFirestoreCollection<Event> = this.angularFirestore.collection("events", ref =>
    ref.where("uid", "==", this.firebaseAuth.auth.currentUser.uid)
  );
  myCollection$: Observable<Event[]> = this.myCollection.valueChanges();

The error that's thrown is:

ERROR in src/app/event/events.service.ts(35,22): error TS2345: Argument of type '"!"' is not assignable to parameter of type 'WhereFilterOp'.

I tried looking for a logical operator that corresponds to !=, but can't seem to find it.

Any help would be greatly appreciated!


Solution

  • According to Firestore doc:

    Queries with a != clause. In this case, you should split the query into a greater-than query and a less-than query. For example, although the query clause where("age", "!=", "30") is not supported, you can get the same result set by combining two queries, one with the clause where("age", "<", "30") and one with the clause where("age", ">", 30).

    So you must compare both '<' and '>' condition

    eventCollection: AngularFirestoreCollection<Event> = 
      this.angularFirestore.collection("events", ref =>
        ref.where("uid", ">", this.firebaseAuth.auth.currentUser.uid)
           .where("uid", "<", this.firebaseAuth.auth.currentUser.uid)
      );