简体   繁体   中英

Get data from subcollection in firestore flutter

In the 1st screen shot there are many documents in collection users . Each documents contains further collection jobPost and that collection contains further documents and its meta data.

在此处输入图像描述

在此处输入图像描述

What I want here is go to the every document of collection users and further subcollection jobPost and fetch all the documents. Suppose first it should go to document 1 in collection users , in the document 1 it should fetch all the documnets in subcollection jobPost then it should go to the 2nd document of collection users and then get all the documents in the subcollection jobPost and so on. what will be the query or implementation to this technique

What you're describing is known as a collection group query , which allows you to query all collections with a specific name. Unlike what the name suggests, you can actually read all documents from all subcollections named jobPost that way with:

FirebaseFirestore.instance.collectionGroup('jobPost').get()...

When performing a query, Firestore returns either a QuerySnapshot or a DocumentSnapshot.

A QuerySnapshot is returned from a collection query and allows you to inspect the collection.

To access the documents within a QuerySnapshot, call the docs property, which returns a List containing DocumentSnapshot classes.

But subcollection data are not included in document snapshots because Firestore queries are shallow. You have to make a new query using the subcollection name to get subcollection data.

FirebaseFirestore.instance
    .collection('users')
    .get()
    .then((QuerySnapshot querySnapshot) {
        querySnapshot.docs.forEach((doc) {
            FirebaseFirestore.instance
               .document(doc.id)
               .collection("jobPost")
               .get()
               .then(...);
        });
    });

** if you not have field in first collection document then its shows italic thats means its delte by default otherwise if you have field in first collection document then you can access it easily so this is the best way that i share **

static Future<List<PostSrc>> getAllFeedPosts()async
  {
    List<PostSrc> allPosts = [];
    var query= await FirebaseFirestore.instance.collection("posts").get();
    for(var userdoc in query.docs)
      {
        QuerySnapshot feed = await FirebaseFirestore.instance.collection("posts")
            .doc(userdoc.id).collection("userPosts").get();
        for (var postDoc in feed.docs ) {
          PostSrc post = PostSrc.fromDoc(postDoc);
          allPosts.add(post);
        }
      }
    return allPosts;
  }

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