dart - 基于子集合属性的 Firestore 查询

标签 dart google-cloud-firestore

我在 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/

相关文章:

flutter - 如何为底部导航栏使用或设置 "on Tap"

dart - 我尝试使用 TextField 的 Controller ,但我收到错误 "NoSuchMethodError: The method ' 调用' was called on null"

file - 读写文件时如何在flutter中修复 "FileSystemException: Cannot open file"?

firebase - Firestore 的规则,强制用户编写 id 等于其自己的 uid 的文档

svg - Flutter 1.1.1 - 依赖项不再有效

asynchronous - 多级异步代码中的 Dart 错误

angular - 如何查询包含一个字段值的对象数组firebase angular?

javascript - 错误 : Value for argument "value" is not a valid query constraint. 无法使用 "undefined"作为 Firestore 值

ios - 以错误的顺序从 Firestore 存储下载 URL

javascript - 未捕获的语法错误 : The requested module '/node_modules/.vite/firebase_firestore.js?v=32c7ddf6' does not provide an export named 'default'