1
votes

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 database structure

Firestore database structure

1

1 Answers

1
votes

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" i.e. userPosts from all user documents. Then you can filter them later by user IDs using Dart if needed.