【问题标题】:How to retrieve all data from a subcollection of all document如何从所有文档的子集合中检索所有数据
【发布时间】:2021-10-26 01:16:38
【问题描述】:

我正在为我的应用程序使用 Flutter。我想检索子集合的所有文档(不仅针对一个用户)并显示在应用程序中。每个用户都有一个 Baggage 子集合和一个 Car 子集合。

这就是我在 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);

如何从子集合“行李”中为所有用户检索数据。如果有最好的方法来构建这些数据并轻松检索,请告诉我。

【问题讨论】:

    标签: firebase flutter android-studio google-cloud-firestore


    【解决方案1】:

    Firestore 有一个叫做 collectionGroup 查询的东西,如果它们具有相同的集合名称,您可以在其中获取所有子集合。可以这样做

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

    这将为您提供所有房间的所有文件。供参考documentation

    【讨论】:

    • collectionGroup 查询可以帮助您从 Firestore 中获取所有集合和子集合,只要它们具有相同的名称。
    • 感谢您的回复。我已经尝试了几件事但没有成功。这是我在使用流时得到的: FirebaseFirestore.instance .collectionGroup('Baggage').orderBy('timestamp', descending: true).snapshots(), [Firestore]: Listen for Query(target=Query( collectionGroup=Baggage按 -timestamp 排序,-name);limitType=LIMIT_TO_FIRST) 失败:状态{code=PERMISSION_DENIED,description=Missing 或权限不足。,cause=null}。请你能告诉我如何为collectionGroup设置规则吗?谢谢。
    • @Vincent 您可以阅读有关在您的行李托运中设置规则的文档。 firebase.google.com/docs/firestore/security/rules-structure
    • 谢谢你,我成功了。唯一的问题是我必须按时间戳删除订单,所以它不是按顺序排列的。但这并不严重。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2022-09-27
    相关资源
    最近更新 更多