Aditya Nigam
Aditya Nigam

Reputation: 999

Firestore: Getting a subcollection from a DocumentSnapshot

I'm using Firestore for backend for a Flutter project, and the database is nested to have sub-collections under documents.Here's the structure:

added

I have the data found from the Root collection, and from there I'm trying to get the sub-collection, but I can't figure how to.

enter image description here

There should be a get() method available but I'm not getting any.

Here's the code for the function:

  void _getNext(DocumentSnapshot doc) async {
        int v = doc.data.length;
        String id = doc.documentID;
        print('length = $v \t id= $id');

        await doc.reference.get().then((val){
        val.data.forEach((k, v){
        print('k = $k  &  v = $v');
          });
        });

       await doc.data.forEach((k,v){
       print("new k = $k, v = $v");
       });

       await doc.reference.collection(id).getDocuments().then((val){
       val.documents.forEach((e){
       print("another k = $e");
         });
       });

 }

And the only response I get from pressing the "Literature" document (from the root collection) is this:

I/flutter (13395): length = 0    id= Literature

There are several sub collections to this document but the returned length is zero. The other blocks of code work fine when I added dummy data to the fields, but that's not needed in my case.

Thank You for your help.

Upvotes: 3

Views: 7374

Answers (2)

mirkancal
mirkancal

Reputation: 5345

There is no get() method for CollectionReference, you need a DocumentReference.

There is nothing wrong with the current situation, you probably want to use getDocuments() since there are no subcollections under your collection, but documents

Notice the alternating pattern of collections and documents. Your collections and documents must always follow this pattern. You cannot reference a collection in a collection or a document in a document.

from: Hierarchical Data

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317467

collection() returns a CollectionReference. As you can see from the API docs, neither CollectionReference, nor it superclass Query have a method called get(). I suspect you want to use getDocuments() instead.

Upvotes: 2

Related Questions