10

I have the following Firestore setup in use:

enter image description here

Now I'd like to receive all documents where the current user (uid given) is in the users object/list. users is an object of references to thje users collection.

Ideally I would want to use this filter from Flutter with the cloud_firestore package, however for now I'm just interested if this is possible at all.

tobire
  • 833
  • 9
  • 17

2 Answers2

14

I found this post which explains, that is not currently possible how I imagined it. I altered my setup to this:

enter image description here

I can now use this query from Flutter to receive the chats for a given user

Firestore.instance
    .collection('chats')
    .where('users.' + _auth.currentUser.uid, isEqualTo: true)
    .snapshots
    .listen((data) {...});

I'm also using this rule to make sure that the user can only access the chats in which he is participating:

match /chats/{chatId} {
  allow read: if resource.users[request.auth.uid];
  // write rule yet to create
}
tobire
  • 833
  • 9
  • 17
  • Instead of setting the value of the userID to `true` in your map, you should put a timestamp here, as described in the article that I linked. With your current answer, you will not be able to sort messages by a particular order, based on time. They'll appear in a random (by document ID) order. – Jason Berryman Mar 29 '18 at 17:30
  • May I ask, how did you solve the Firestore indexing issue. When adding another .where clause, firestore asks to add an index with the UID value which obviously wouldn't make sense. – KasparTr Oct 10 '20 at 09:54
  • If I wanted to update one of the documents using the 'where' clause, how would that be done? (The doc id is not known, thats why I'm using the 'where' clause) – Aryan Sethi Nov 08 '21 at 14:22
  • Nice, thank you! That saved me quite some time... I can't believe that the flutter firestore has such weak querying capabilities. :( – tafaust Nov 14 '21 at 20:48
1

Yes. This is possible. However you will need to store you user references as a map of values and create a reference to query with in your client (based on the user ID). Take a look at the documentation: Working with Arrays, Lists and Sets

Jason Berryman
  • 4,760
  • 1
  • 26
  • 42