【问题标题】:The method 'updateData' isn't defined for the type 'Query'. Futter, Cloud Firestore没有为“查询”类型定义方法“updateData”。 Futter, Cloud Firestore
【发布时间】:2020-11-23 17:12:00
【问题描述】:
我想根据查询更新文档中的数据。这是我的代码:
Firestore.instance
.collection("Categories")
.where("userEmail", isEqualTo: "${user?.email}")
.updateData({"category_budget_remaining": _remainingCategoryBudget2})
.then((value){});
我收到以下错误:没有为类型“查询”定义方法“updateData”
【问题讨论】:
标签:
firebase
flutter
google-cloud-firestore
【解决方案1】:
where() 之后你需要获取文档然后进行更新
where(...).getDocuments().then((val)=>
val.documents.forEach((doc)=> {
doc.reference.updateData({...})
});
});
此代码选择并更新所有符合 where 条件的文档。如果您只想为 1 个文档执行此操作,则只需在 getDocuments() 之前添加 .limitTo(1)。
【解决方案2】:
从 API 文档中可以看出,where() 返回一个 Query,而 Query 没有名为 updateData() 的方法。所以,你在这里看到的并不奇怪。
Firestore 不提供像 SQL“update where”命令那样批量更新文档的方法。您需要做的是执行要更改的文档的查询,迭代结果集中的文档,并单独更新每个文档。是的,它需要为每个文档读取一个文档才能更改,不,没有其他选择。
【解决方案3】:
我的回答与@Habib Mahamadi 相似,但这是实现此功能的正确且唯一的方法,我的回答略有不同,因为 firebase 更改了函数名称。
Firestore.instance
.collection("Categories")
.where("userEmail", isEqualTo: "${user?.email}")
.then((value)=> value.docs.forEach((element){element.reference.update({"" : ""})});