简体   繁体   中英

How can I get a collection inside a QuerySnapshot

On the explore page, I get() the entire users collection to create a user list and search results. Inside each of those user documents is a collection posts that I also need to get to create a GridView of each post. I want to reuse that users collection QuerySnapshot instead of fetching each posts collection again to save money. Is this possible?

Here is my current function:

  void fetchUsers() async {
    final userRef = FirebaseFirestore.instance.collection('users');

    final QuerySnapshot result = await userRef.get();

    final docs = result.docs.asMap();

    docs.forEach((index, value) {
      final profile =
          ProfileObject.fromJson(value.data() as Map<String, dynamic>);

      usersList.add(UserSearchResult(profile, value.id));

/// Below is the code for getting the posts, not working, need ideas

      final QuerySnapshot postsResult = value.get('posts');

      final posts = postsResult.docs.asMap();

      posts.forEach((index, value) {
        final post = Post.fromJson(value.data() as Map<String, dynamic>);

        postsList.add(post);
      });
    });


    print(usersList);
    print(postsList);
  }

Here is the structure of my Firestore:

  • users
    • uid (doc)
      • posts (collection)
      • info (fields)
    • uid (doc)
      • posts (collection)
      • info (fields)

It is not possible to call a collection to get all sub-collections. You should restructure your database to include sub-collection data in document itself. You can use a map or list for that. But remember, calling everything in one go may end up in slow performance and you might end up losing your customers. So the best way is to include the info in every posts' documents. That way, you won't loss your money and user won't feel lag in performance.

It is not possible. You fetch a document, then fetch the (sub)collection under it.

Subcollection data are not included in the initial document snapshots because Firestore queries are shallow. There shouldn't be any cost savings that you can do there?

See the similar Q&A: Firestore: Get subcollection of document found with where

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