【问题标题】:How to remove a nested property from Firestore collection如何从 Firestore 集合中删除嵌套属性
【发布时间】:2022-02-18 21:49:01
【问题描述】:

我正在学习如何在 Flutter 中使用带有 BLoC 模式的“Firestore”。我正在关注 Sagar Suri 的本教程。 https://medium.com/codechai/when-firebase-meets-bloc-pattern-fb5c405597e0。但是,本教程很旧,我正在尝试删除错误并更新它以用于学习目的。我面临2个问题。第一个问题与“updateGoal”功能有关。例如,他从 collection 中复制了目标值,将其转换为 String,然后更新了该值。我在这里遇到错误。任何人都可以帮助我,我如何从用户那里提取目标价值,复制到地图中,投射然后更新。 。这就是我想要做的。

Future<void> uploadGoal(String title, String documentId, String goal) async {
    DocumentSnapshot doc =
    await _firestore.collection("users").doc(documentId).get();
    Map<String, String> data = doc.data()! as Map<String, String>;
    /****/
    //Getting error here "The operator '[]' isn't defined for the type 'Object? Function()'."
    Map<String, String> goals = doc.data["goals"] != null
         ? doc.data["goals"].cast<String, String>()
         : null;
    /****/
    if (data != null) {
      data[title] = goal;
    } else {
      data = Map();
      data[title] = goal;
    }
    return _firestore
        .collection("users")
        .doc(documentId)
        .set({'goals': data, 'goalAdded': true},  SetOptions(merge: true));
  }

类似的问题,我在 removeGoal 函数中遇到。

void removeGoal(String title, String documentId) async {
    DocumentSnapshot doc =
    await _firestore.collection("users").doc(documentId).get();
    Map<String, String> data = doc.data()! as Map<String, String>;
    //How to remove goals title from collection here
    goals.remove(title);
    if (goals.isNotEmpty) {
      _firestore
          .collection("users")
          .doc(documentId)
          .update({"goals": goals});
    } else {
      _firestore
          .collection("users")
          .doc(documentId)
          .update({'goals': FieldValue.delete(), 'goalAdded': false});
    }
  }

有人可以帮助我吗?谢谢。

【问题讨论】:

  • “我在这里遇到错误”请编辑您的问题以显示确切的错误消息以及该错误的堆栈跟踪。
  • @Dharmaraj,是的,我检查了这个,但我正在考虑嵌套属性。例如,目标有 2 个属性构建时间和旅行,我认为教程目标标题的意思是“构建时间”。我从 Firestore 了解这一点,但我正在尝试从教程中学习,这就是为什么我需要以他们的方式做事。

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


【解决方案1】:

这看起来不对:

Map<String, String> data = doc.data()! as Map<String, String>;

虽然文档中的所有键都是字符串,但 goals 值是对象/字典而不是字符串。所以充其量你可以将它转换为:

Map<String, dynamic> data = doc.data()! as Map<String, dynamic>;

一旦你这样做了,你注释掉以获取 goals 字段的语句应该可以工作,但它不会:使用更新的代码提供更新的问题,以及确切的错误消息和堆栈跟踪你明白了。

【讨论】:

  • 谢谢,但我需要删除或更新目标属性。从示例“构建时间”或“旅行”中,我认为目标标题是构建时间。
猜你喜欢
  • 1970-01-01
  • 2012-10-25
  • 2021-08-27
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 2021-08-14
相关资源
最近更新 更多