【问题标题】:Flutter - Can't get collection from firestoreFlutter - 无法从 Firestore 收集
【发布时间】:2022-01-15 17:37:51
【问题描述】:
    _getLatestCompletedWorkout() async {
  try {
    QuerySnapshot workouts;
    workouts = await FirebaseFirestore.instance
        .collection('users')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .collection('workouts')
        .get();
    for (var workout in workouts.docs) {
      print('WORKOUT = ');
      print(workout);
    }
.....

我真正需要的是保存最后一个文档;但在此之前,我只是想获取“锻炼”系列; trainings.docs 列表始终有 0 个项目。数据库中有 2 个项目。这段代码有什么问题?还有如何获取最后保存的项目?

【问题讨论】:

标签: flutter dart google-cloud-firestore get


【解决方案1】:

正如弗兰克所说:

你可以参考Alex的回答here

实现这一点的最简单方法是添加日期 集合中每个对象的属性,然后简单地查询它 根据这个新的属性descending并调用limit(1)函数。

这是必需的查询:

this.historyRef = afs.collection<History>('history', ref => ref.orderBy('date', 'desc').limit(1));
this.history = this.historyRef.snapshotChanges().map(actions => {
    return actions.map(a => {
        const data = a.payload.doc.data() as Hisotory;
        const docId = a.payload.doc.id;
        return { docId, ...data };
    });
});

【讨论】:

  • 是的,弗兰克的评论有帮助。我用日期保存数据并按降序检索并取第一个元素。
猜你喜欢
  • 1970-01-01
  • 2020-11-23
  • 2023-03-15
  • 1970-01-01
  • 2022-09-23
  • 2022-06-24
  • 2020-10-30
  • 2020-02-03
  • 2021-11-25
相关资源
最近更新 更多