2

Hello I want to get all docs from a collection in one shot without knowing the docs id's since they are random. Inside each doc I have some data but all I need is the doc itself than I will take the data from each and every one no problem.

I get null every time.

Does anyone know what am I doing wrong?

Thank you in advance.

This is the code :

import 'package:cloud_firestore/cloud_firestore.dart';

Future<Map<String, dynamic>> getVisitedCountries(String ID) async {
  Map<String, dynamic> val = <String, dynamic>{};
  await FirebaseFirestore.instance
      .collection('users')
      .doc(ID)
      .collection('PersonalData')
      .doc(ID)
      .collection('Passport')
      .doc(ID)
      .collection('VisitedCountries')
      .doc()
      .get()
      .then((value) {
    if (value.data().isEmpty) {
      print("User not found");
    } else {
      val = value.data();
    }
  }).catchError((e) {
    print(e);
  });

  return val;
}

This is the structure in the Cloud Firestore enter image description here

Alex97
  • 401
  • 1
  • 8
  • 21
  • Are you looking for [collection group query](https://stackoverflow.com/q/58270085/13130697)? `Firestore.instance.collectionGroup('VisitedCountries').getDocuments()`. This will return VisitedCountries of all users. – Dharmaraj Mar 26 '22 at 20:25
  • I've already tried that but it tells me that getDocuments() does not exist and I can not do .then after that – Alex97 Mar 26 '22 at 20:29
  • Can you try using `get()` instead of `getDocuments()` as in the [documentation](https://firebase.flutter.dev/docs/firestore/usage/#querying) ? – Dharmaraj Mar 26 '22 at 20:32
  • As you can see in the pic I am using it and nothing happens I get null – Alex97 Mar 26 '22 at 20:34
  • Have you tried `get()` with `collectionGroup()`? – Dharmaraj Mar 26 '22 at 20:35
  • 1
    getDocuments is deprecated. Have a look at this. https://stackoverflow.com/questions/46611369/get-all-from-a-firestore-collection-in-flutter/65589664#65589664 – Kantine Mar 26 '22 at 20:36

1 Answers1

1

So for everyone who is having this problem, this is the way to solve it. I solved it thanks to the user : Kantine

Solution : code :

import 'package:cloud_firestore/cloud_firestore.dart';

Future<Iterable> getVisitedCountries(String ID) async {
  // Get data from docs and convert map to List
  QuerySnapshot querySnapshot = await FirebaseFirestore.instance
      .collection('users')
      .doc(ID)
      .collection('PersonalData')
      .doc(ID)
      .collection('Passport')
      .doc(ID)
      .collection('VisitedCountries')
      .get();
  final val = querySnapshot.docs.map((doc) => doc.data());
  return val;
}

I used a query snapshot to get the data and then mapped it.

Alex97
  • 401
  • 1
  • 8
  • 21