【问题标题】:Query Firestore documents inside a nested collection in Flutter在 Flutter 的嵌套集合中查询 Firestore 文档
【发布时间】:2021-09-29 17:33:52
【问题描述】:

是否可以在不向 .get() 方法提供参数的情况下查询 Firestore 中的嵌套文档? 我想通过遍历所有用户 id 并获取所有 userPosts 来获取所有用户创建的所有帖子。

下面是我使用的代码。

非常感谢。

getAllPosts() {
    final CollectionReference postsRef = FirebaseFirestore.instance
        .collection("posts");
    var allPosts = postsRef.get().then((value) =>
        value.docs.forEach((snapshot) {
          var userPostsRef = postsRef.doc(snapshot.id);
              var subCollection = userPostsRef.collection("userPosts").get();
              print("subCollection $subCollection");
        })

    );
    print("allPosts $allPosts");

  }

print("subCollection $subCollection"); 在控制台上不显示任何内容。 print("allPosts $allPosts"); 在控制台上显示“未来”的实例

Firestore 结构:

posts -> userId -> userPosts -> postId -> {实际的帖子文档}

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    您正在寻找collectionGroup 查询。

    FirebaseFirestore.instance
      .collectionGroup('userPosts')
      .get((snpashot) {
        print(snapshot.size)
      });
    

    这将从名为“userPosts”的所有子集合中获取所有文档,即来自所有用户文档的 userPosts。然后,如果需要,您可以稍后使用 Dart 按用户 ID 过滤它们。

    【讨论】:

      猜你喜欢
      • 2021-04-08
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 2021-09-05
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多