简体   繁体   中英

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? I would like to get all posts created by all users by looping through all the user ids and getting all the userPosts.

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}

Firestore 数据库结构

Firestore 数据库结构

You are looking for collectionGroup queries.

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. Then you can filter them later by user IDs using Dart if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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