1

I have the following Firestore structure:

attendance (collection)
│
└─── 11-12-2076 (document)
    │
    └─── students (collection)
        │
        └─── d8281c00-fd7d-11ed-9234-3fbd868d12b9 (document)

And as a path:

/attendance/5-29-2023/students/afe9e3f0-fd77-11ed-a0fc-596eeda998cb

And as an image:

enter image description here

And I'm trying to fetch all the documents under the attendance collection. Hence, I'm using

.collection('attendance').get()

in order to receive all the documents/subcollections under attendance. however, if I print out the docs, it always returns an empty list []. Here is my code:

final attendanceCollection = FirebaseFirestore.instance.collection('attendance');

final QuerySnapshot attendanceSnapshot = await attendanceCollection.get();

print('attendanceSnapshot length is: ${attendanceSnapshot.docs.length}');

But the above output is always 0:

attendanceSnapshot length is: 0

What am I doing wrong? Why isn't the collection returning any data?

Essentially, what I'm trying to do is query all the documetns:

Future<void> exportAttendanceData() async {
    final attendanceCollection =
        FirebaseFirestore.instance.collection('attendance');
    final QuerySnapshot attendanceSnapshot = await attendanceCollection.get();

    for (final attendanceDoc in attendanceSnapshot.docs) {
      final studentsCollection =
          attendanceCollection.doc(attendanceDoc.id).collection('students');
      final QuerySnapshot studentsSnapshot = await studentsCollection.get();
      for (final studentDoc in studentsSnapshot.docs) {
        print(studentDoc.data()); // Print the data of each student document
      }
    }
  }

Here are my Firestore Security rules (it's not blocking anything):

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if
          request.time < timestamp.date(2023, 6, 24);
    }
  }
}

What I tried:

  • Checked the security rules.
  • Checked for any typos with the collection name.
  • Made sure flutter doctor -v returns no errors/warnings.
Question
  • How can I get all the documents/collections under the attendance collection? Why is .collection('attendance').get() returning an empty array?
MendelG
  • 14,885
  • 4
  • 25
  • 52

1 Answers1

2

Read operations in Firestore are shallow, so reading from /attendance will only return documents in that specific collection - not from lower level subcollections.

If you want to read all students, you can use a collection group query to do so.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807