简体   繁体   English

在 Flutter 中的嵌套集合中查询 Firestore 文档

[英]Query Firestore documents inside a nested collection in Flutter

Is it possible to query nested documents in Firestore without providing an argument to the .get() method?是否可以在不向.get()方法提供参数的情况下查询 Firestore 中的嵌套文档? I would like to get all posts created by all users by looping through all the user ids and getting all the userPosts.我想通过遍历所有用户 ID 并获取所有用户帖子来获取所有用户创建的所有帖子。

Below is the code I used.下面是我使用的代码。

Thank you very much.非常感谢你。

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"); doesn't show anything on the console.控制台上不显示任何内容。 print("allPosts $allPosts"); shows Instance of 'Future' on the console.在控制台上显示“未来”的实例

Firestore structure:火库结构:

posts -> userId -> userPosts -> postId -> {The actual post document} posts -> userId -> userPosts -> postId -> {实际的帖子文档}

Firestore 数据库结构

Firestore 数据库结构

You are looking for collectionGroup queries.您正在寻找collectionGroup查询。

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

This will fetch all documents from all sub-collections named "userPosts" ie userPosts from all user documents.这将从名为“userPosts”的所有子集合中获取所有文档,即来自所有用户文档的 userPosts。 Then you can filter them later by user IDs using Dart if needed.然后,如果需要,您可以稍后使用 Dart 通过用户 ID 过滤它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM