aris
aris

Reputation: 143

Firestore query based in subcollection attribute

I have the next structure of content in firestore (a channels collection, and a followers sub-collection in every channel):

channels (is a collection):
  - {channel id} (channel document id)
    - name,
    - description, ...
    - followers (subcollection in every channel)
      - {user id} (follower document id)
        - state (user attribute) = 1 (is active),

I'm trying a query to get all channels of one follower. something similar to:

// dart
db.collection('channels').where('followers.$uid.state', isEqualTo: 1).snapshots();

Where $uid is a valid user id. Then, query result must return all channels where the user is as a follower. I could do it with an array of user ids in channel, but I'll have a big number of followers and in arrays, I have to read and write complete array in every modification, when I add or remove followers.

Thanks!

Upvotes: 0

Views: 88

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317948

The only way to do this is not going to be just a simple query. You can use a collection group query to find all the follower documents among all channels that match some criteria, but you will have to extract the channel IDs out of the paths of those documents using the references in the document snapshots.

db.collectionGroup('followers').where('$uid.state', isEqualTo: 1)

Run that query, then iterate each DocumentSnapshot. Each snapshot will have a reference property that contains the full path of the document. Use the parent property of each reference to work your way up to the DocumentReference that refers to the channel, and add its documentID to a set. After you're done iterating, that set will contain everything you need.

Upvotes: 1

Related Questions