Flutter Flatter/Firestore—如何在文档数组中的字段上运行事务更新

Flutter Flatter/Firestore—如何在文档数组中的字段上运行事务更新,flutter,google-cloud-firestore,Flutter,Google Cloud Firestore,我知道我可以在文档的顶级字段中执行此操作。但我试图在文档数组中的一个字段上运行事务更新 以下是我的“测验”文档的结构: { title: '123', questions: [ { title: 'question1', answers: [ { title: 'answer1', votes: 0 } ] } ] } 这是我正在使用的代码,它在“wait t

我知道我可以在文档的顶级字段中执行此操作。但我试图在文档数组中的一个字段上运行事务更新

以下是我的“测验”文档的结构:

{
  title: '123',
  questions: [
    {
      title: 'question1',
      answers: [
        {
          title: 'answer1',
          votes: 0
        }
      ]
    }
  ]
}
这是我正在使用的代码,它在“wait tx.update…”上失败,因为我传递的字符串路径是“问题[0]。答案[0]。投票”。有可能吗?还是我必须提取整个文档,更新值并替换它

final DocumentReference postRef = Firestore.instance.document('quizes/' + id);
Firestore.instance.runTransaction((Transaction tx) async {
  DocumentSnapshot postSnapshot = await tx.get(postRef);
  if (postSnapshot.exists) {
    await tx.update(postRef, <String, dynamic>{'questions[0].answers[0].votes': postSnapshot.data['questions'][0]["answers"][0]["votes"] + 1});
  }
}); 
final DocumentReference postRef=Firestore.instance.document('quizes/'+id);
Firestore.instance.runTransaction((事务发送)异步{
DocumentSnapshot postSnapshot=wait tx.get(postRef);
如果(postSnapshot.exists){
等待tx.update(postRef,{'questions[0]。答案[0]。投票:postSnapshot.data['questions'][0][“answers”][0][“votes”]+1});
}
}); 
有可能吗?还是我必须提取整个文档,更新值并替换它

final DocumentReference postRef = Firestore.instance.document('quizes/' + id);
Firestore.instance.runTransaction((Transaction tx) async {
  DocumentSnapshot postSnapshot = await tx.get(postRef);
  if (postSnapshot.exists) {
    await tx.update(postRef, <String, dynamic>{'questions[0].answers[0].votes': postSnapshot.data['questions'][0]["answers"][0]["votes"] + 1});
  }
}); 
为了在Firestore中更新数组中的字段,您必须获取数组,更新所需的字段,然后更新文档。您可以使用事务来实现这一点。下面您将找到有关的一些详细信息

让我知道这是否有用

有可能吗?还是我必须提取整个文档,更新值并替换它

final DocumentReference postRef = Firestore.instance.document('quizes/' + id);
Firestore.instance.runTransaction((Transaction tx) async {
  DocumentSnapshot postSnapshot = await tx.get(postRef);
  if (postSnapshot.exists) {
    await tx.update(postRef, <String, dynamic>{'questions[0].answers[0].votes': postSnapshot.data['questions'][0]["answers"][0]["votes"] + 1});
  }
}); 
为了在Firestore中更新数组中的字段,您必须获取数组,更新所需的字段,然后更新文档。您可以使用事务来实现这一点。下面您将找到有关的一些详细信息

让我知道这是否有用