我在 firestore 中有下一个内容结构( channel 集合和每个 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),
我正在尝试查询以获取一位关注者的所有 channel 。类似于:
// dart
db.collection('channels').where('followers.$uid.state', isEqualTo: 1).snapshots();
其中 $uid 是有效的用户 ID。然后,查询结果必须返回用户作为关注者的所有 channel 。
我可以在 channel 中使用一组用户 ID 来做到这一点,但是我会有大量的追随者,并且在数组中,当我添加或删除追随者时,我必须在每次修改中读取和写入完整的数组。
谢谢!
最佳答案
做到这一点的唯一方法不仅仅是一个简单的查询。您可以使用 collection group query要在符合某些条件的所有 channel 中查找所有关注文档,但您必须使用文档快照中的引用从这些文档的路径中提取 channel ID。
db.collectionGroup('followers').where('$uid.state', isEqualTo: 1)
运行该查询,然后迭代每个 DocumentSnapshot .每个快照都有一个 reference property包含文档的完整路径。使用 parent property每个引用的工作都可以达到DocumentReference指的是 channel ,并添加其documentID到一组。完成迭代后,该集合将包含您需要的所有内容。
关于dart - 基于子集合属性的 Firestore 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60606579/