Mehboob
Mehboob

Reputation: 57

how to retrieve unknown sub collection from document in flutter

I have the following code with the objective of retring all the documents like this: Collection('A').document(currentUser), this should give me the document YRZ1**** as you may see in the first image. Now what I want to do is get all the documents in the t22o9*** subcollection, as showned on the second image, how can I do that?

var docPath=Firestore.instance.document('Messages/$currentUser');

docPath.snapshots().listen((event) {
  print('Hello  12 ${event.data}');

});

enter image description here

enter image description here

Upvotes: 2

Views: 1064

Answers (1)

Rafael Lemos
Rafael Lemos

Reputation: 5819

In order to get data from subcollection you can do the following:

var db = Firestore.instance;
//This is a reference to the YRZ1**** doc
var messagesDoc = db.collection('Messages').document('Messages/$currentUser');
//collectionId is the t22o9*** id, you need to have this set previosly in your code
var docList = [];
messagesDoc.collection(collectionId)
           .getDocuments()
           .then((QuerySnapshot snapshot) {
               snapshot.documents.forEach((doc) => docList.add(doc)'));
           });

With this code, docList will be a list of the documents located at your subcollection t22o9*** of the YRZ1*** document.

Also you can check this link with some examples on how to get data from firestore using flutter.

EDIT:

As per what you have clarified on the comments, getting the subcollection data is a bit more complicated with subcollections that were created dynamically, as you can see on this link, which I assume is the case you have. The most feasible solution in your case would be to create a list of ids of subcollections in your parent document, so for example your YRZ1*** document would have this structure

document
   id: YRZ1***
   subCollectionIds : [subCollectionId1, subCollectionId2,...]
   subCollection1
   subCollection2
   ...
   subCollectionN

Having this structure you could use this code to retrieve the list of subcollections and the first document of each subcollection, ordered by whatever field you'd like:

var db = Firestore.instance;
var listFirstDocSub = []
//This is a reference to the YRZ1**** doc
db.collection('Messages')
  .document('Messages/$currentUser')
  .getDocument()
  .then((DocumentSnapshot doc) {
      var listSubCollections = doc["subCollectionIds"];
      listSubCollections.forEach((id) {
          db.collection('Messages')
            .document('Messages/$currentUser')
            .collection(id)
            .orderBy("WHATEVER_FIELD_YOU_DECIDE")
            .limit(1)
            .getDocuments()
            .then((DocumentSnapshot snapshot) {
                listFirstDocSub.add(snapshot);
            }) 
      });
});

NOTE: With this approach, everytime you add a new subcollection, you will also need to add it's id to the subCollectionIds list.

Hope This helps.

Upvotes: 1

Related Questions