在Flutter中查询后如何更新Firestore文档 [英] How to update a Firestore document after querying in Flutter
问题描述
查询完要更新的文档后,我试图弄清楚如何更新文档.这是我想出的代码:
I am trying to figure out how to update my document after I query the one I want to update. Here is the code I came up with:
Firestore.instance.collection("Social_Posts").where(data["postTitle"], isEqualTo: "postTitle").where(data["postContent"], isEqualTo: "postContent")
.snapshots()
.listen((event) {print("hh");});
每当执行此查询以查找正确的文档时,我都想通过在其上添加数字来更新该文档.
Whenever I perform this query to find the correct document, I would like to update the document by adding a number to it.
推荐答案
可以从内部更新文档,最简单的方法肯定是使用documentID并增加值Firestore具有特殊属性, FieldValue.increment(1) .使用此功能,您可以轻松地增加字段.
It is possible to update the document from inside, The easier way to do that would definitely be to use the documentID and to increment the value Firestore has a special property, FieldValue.increment(1). Using this you can easily increment a field.
假设您要在文档中增加1的字段是"numberField".
Lets say the field in the document you want to increment by 1, is "numberField".
使用异步/等待样式的更新代码:
onTap: () async {
setState(() {
_title = data["postTitle"];
_content= data["postContent"];
});
print(_title);
print(_content);
QuerySnaphot snapshot = await Firestore.instance.collection("Social_Posts")
.where("postTitle" , isEqualTo: _title)
.where("postContent", isEqualTo: _content)
.getDocuments();
if(snapshot.documents.isNotEmpty)
{
snapshot.documents.forEach((doc){
doc.reference.updateData({"views" : FieldValue.increment(1),});
});
}
}
numberField将增加,而无需进行额外的调用来知道当前值.
The numberField will be incremented without needing to make an extra call to know the present value.
您在 .where()方法
这篇关于在Flutter中查询后如何更新Firestore文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!