简体   繁体   中英

How to retrieve all data from a subcollection of all document

I am using Flutter for my app. I want to retrieve all document (not only for one user) of a subcollection and display in the app. Each user has a subcollection of Baggage and a subcollection of Car.

This is how I store in Firebase:

String createAt = DateTime.now().millisecondsSinceEpoch.toString();
var ref = FirebaseFirestore.instance.collection('Trips').doc('userId').collection('Baggage').doc(createAt);
FirebaseFirestore.instance.runTransaction((transaction) async {transaction.set(ref, {
    'departure': city1.text, 
    'destination': city2.text, 
    'weight': _weightcontroller.text, 
    'id': userId, 
    'departureDate': date.text, 
    'username': firstname, 
    "timestamp": createAt,
  }); 
});
    
    
var ref1 = FirebaseFirestore.instance
  .collection('Trips')
  .doc('userId')
  .collection('Cars')
  .doc(createAt);

How to retrieve data from subcollection 'Baggage' for all users. If there is best way so structure these data and retrieve easily, please let me know.

Firestore has something called collectionGroup query where you can get all subcollections if they have same collection name. Which can be done as

FirebaseFirestore.instance.collectionGroup('Baggage').get();

This will give you all the documents across all rooms. For reference documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM