首页 > 解决方案 > 如何使用颤振更新firestore中地图内的项目

问题描述

我对更新 Firestore 中的项目有疑问。假设我们有以下结构

"content" -> document -> 
"questions": 
[
{
"q" : "Are you good?", 
"info" : "Just say yes or no"
}, 
{
"q" : "are you playing ball", 
"info" : "football, soccer, basketbal.."
}
]

现在用户正在回答一个问题,我想将答案保存在特定问题的映射中的数组中,例如:

"content" -> document -> 
"questions": 
[
{
"q" : "Are you good?", 
"info" : "Just say yes or no",
"answer" : "yes"
}, 
{
"q" : "are you playing ball", 
"info" : "football, soccer, basketball..",
"answer" : "no"
}
]

第一次没问题,问题就这样保存了,原始问题的快照,当前索引和给定的答案:

void _onPressed(AsyncSnapshot snapshot, index, answer) async {
var firebaseUser = FirebaseAuth.instance.currentUser;
Map<String, dynamic> someData = {
    "q": snapshot.data!["questions"][index]["q"],
    "info": snapshot.data!["questions"][index]["info"],
    "answer": answer
  };
await firestoreInstance
      .collection("test")
      .doc(firebaseUser.uid)
      .collection("content")
      .doc("document")
      .update({
    "questions": FieldValue.arrayUnion([someData]),
  }).then((_) {
    print("success!");
  });
}

但是,如果用户返回问题并更改他的答案,它只会创建一个新条目,而不是将特定问题的“是”更改为“否”:

"content" -> document -> 
"questions": 
[
{
"q" : "Are you good?", 
"info" : "Just say yes or no",
"answer" : "yes"
}, 
{
"q" : "are you playing ball", 
"info" : "football, soccer, basketball..",
"answer" : "no"
},
{
"q" : "are you playing ball", 
"info" : "football, soccer, basketball..",
"answer" : "yes"
}
]

有什么方法可以更改数组内地图中的 1 项(答案)?也许数据模型没有意义?我真的不知道,我尝试了很多不同的方法......

谢谢帮助

标签: firebasefluttergoogle-cloud-firestoreflutter-web

解决方案


推荐阅读