javascriptgoogle-cloud-firestoreangularfire

Firestore array-contains-any is not working properly


"@angular/fire": "5.2.3", 
"firebase": "7.4.0",

Note: members is an array and 0,1,2 is map data structures.

enter image description here

service.ts

 getUserChatGroups(uid: string): Observable<DocumentChangeAction<MessageGroupMemberModel>[]> {
    return this.afs.collection<MessageGroupMemberModel>(`messageGroups`, ref => ref.where('members', 'array-contains-any', [uid])).snapshotChanges();
  }

page.ts

 init(): void {
    const uid: string = this.authService.getUserUid();
    this.chatService.getUserChatGroups(uid).subscribe(res => {
      console.log(res);
    },
      err => console.log(err),
      () => console.log('request completed')
    );

  }

No errors. But it doesn't return any value. But it has values. Is there something wrong with my query?


Solution

  • The array-contains-any (and also the array-contains) operator check whether the array contains an element that exactly-and-completely matches the information that you pass into the call. So in your case, you need to pass in both the id and the joinDateTime in order to match.

    ref.where('members', 'array-contains-any', [{ id: uid, joinedDateTime: ... }])
    

    If you don't know the joinedDateTime for the user, you can't query the array in your current data structure. The normal solution is to store a separate array field memberIds in the document too, which contains just the UIDs of the members. Then you can find the members by querying on that field:

    ref.where('memberIds', 'array-contains', [uid])
    

    Or

    ref.where('memberIds', 'array-contains-any', [uid, uid2, uid3])