Ibanez1408
Ibanez1408

Reputation: 5078

Query a document value in a nested collection in firebase

I need to get the values from a document with this schema in Firebase:

COLLECTION => DOCUMENT => COLLECTION => DOCUMENT 
userPolls  => userId   => dailyPolls => 20200825 => pollDate: "2020/08/25"
                                                    status:   "Under PUM"
                                                    statusCode: "pum"
                                                    uid: "zwQnrrBdNCemWyXEW2LHmw8LejA2"

enter image description here

This is my attempt at it. But I think I am getting it wrong in flutter

final CollectionReference userPollCollection =
      Firestore.instance.collection('userPolls');
Future getPoll() async {
    final DateTime now = DateTime.now();
    final DateFormat formatter = DateFormat('yyyy/MM/dd');
    final String formatted = formatter.format(now);
    var pollDate = formatted;
    
    var docRef = await applicationUser
        .document(userId)
        .collection('dailyPolls')
        .document(pollDate);
    docRef.get().then((onValue) => {print(onValue.data['status'])});
  }

I know that this is not right. Can you please show me how? Thank you.

EDIT For reference, this is how I ADD data to the firestore db:

Future setPoll(UserPoll userPoll) async {
    var dt = userPoll.pollDate.replaceAll('/', '');
    return await userPollCollection
        .document(userId)
        .collection('daillyPolls')
        .document(dt)
        .setData({
      'uid': userId,
      'pollDate': userPoll.pollDate,
      'status': userPoll.status,
      'statusCode': userPoll.statusCode
    });
  }

This is how I try to get it

Future getPoll() async {
    final DateTime now = DateTime.now();
    final DateFormat formatter = DateFormat('yyyy/MM/dd');
    final String formatted = formatter.format(now);
    var pollDate = formatted;
    var dt = pollDate.replaceAll('/', '');

    var docRef = userPollCollection
        .document(userId)
        .collection('dailyPolls')
        .document(dt);

    docRef.get().then((onValue) {
      print(onValue.data);
    });
  }
}

If I use this code based on the help of Peter Haddad, I get a null value when printing my result.data

Upvotes: 0

Views: 39

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80944

You have to do the following:

var docRef = Firestore.instance.collection("userPolls").document(userId).collection('dailyPolls').where("pollDate", isEqualTo: pollDate);
var result = await docRef.getDocuments();
   result.documents.forEach((result) {
      print(result.data);
     });
  });

Since pollDate is an attribute inside a document then you can use the where() method to query and get the document

Upvotes: 1

Related Questions