1
votes

I need to get the data of the first document (only) of my sub collection.

I have tried this first solution :

void _getOwner(accommodation) async {

    await FirebaseFirestore.instance
        .collection('Users')
        .doc(uid)
        .collection('Accommodation')
        .doc(accommodation.id)
        .collection('Owner')
        .limit(1)
        .get()
        .then((value){
          print(value.data());
        });
  }

But I have this error message :

The method 'data' isn't defined for the class 'QuerySnapshot'.

  • 'QuerySnapshot' is from 'package:cloud_firestore/cloud_firestore.dart' ('../../../.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.15.0/lib/cloud_firestore.dart'). Try correcting the name to the name of an existing method, or defining a method named 'data'. print(value.data());

Then I have tried this solution :

  void _getOwner(accommodation) async {

    await FirebaseFirestore.instance
        .collection('Users')
        .doc(uid)
        .collection('Accommodation')
        .doc(accommodation.id)
        .collection('Owner')
        .get()
        .then((QuerySnapshot querySnapshot) => {
          querySnapshot.docs.forEach((doc) {
            print(doc["LastName"]);
          })
    });
  }

It works, but I need the LastName of my first Owner document, not "forEach"... what should I do ?

1
Please show the actual problem, not the code you think is right - console.log's, error messages, etc. There are many ways the above could generate an error. => does the document exist? => does the field exist in the document? => is the field name actually 'email'? => DocumentSnapshot.data is an object, not an array, although the [ ] syntax can often work. - LeadDreamer
I have updated my post to give you more informations. - user15087335

1 Answers

0
votes

In your section:

.then((QuerySnapshot querySnapshot) => {
          querySnapshot.docs.forEach((doc) {
            print(doc["LastName"]);
          })
    });

querysnapshot.docs is an array of QueryDocumentSnapshots (NOT the final documents), and can be addressed as an array. I caution that the concept of "first" is a tricky one in Firestore - you should define your own order, and use an .orderBy() in your code; otherwise it will be in order of documentID, which I hope, for performance reasons, is a pseudo-random code. Assuming it is actually the "first" in whatever order you have described, you could do:

.then((QuerySnapshot querySnapshot) => {
        print(querySnapshot.docs[0].data.LastName);
    });

As a general rule, using the dot(.) notation is better for fixed, known field names; the array notation doc[variable] is best left for, well, when you need to use a variable to reference the fieldname.