firebase - 正在创建新文档而不是更新
问题描述
我onPress
在编辑页面上有一个 - 它应该在编辑和保存时更新文档。
但是,它目前正在使用该数据创建一个新文档。
onPressed: () async {
//controllers...
await updateContact(context);
Navigator.pop(context, widget.contact);
}
.
final db = FirebaseFirestore.instance;
.
Future updateContact(context) async {
final uid = await TheProvider.of(context).auth.getCurrentUID();
await db
.collection('userData')
.doc(uid)
.collection('Contacts')
.doc(widget.contact.documentId)
.set({
'Name': oneController.text,
'PhoneNumber': int.tryParse(twoController.text),
'Location': threeController.text,
'Rating': int.tryParse(fourController.text),
'Instagram': fiveController.text,
'Birthday': int.tryParse(sixController.text),
'Notes': sevenController.text},
SetOptions(merge: true));
.
Contact.fromSnapshot(DocumentSnapshot snapshot) :
//...
documentId = snapshot.id;
我不确定如何最好地解决这个问题。
解决方案
是的,使用set()
将覆盖 Firestore 中已经存在的所有数据。
是的,使用update
是要走的路,但请记住不要调用.toJson()
整个对象,因为更新只需要需要更新的字段。因此,如果您使用整个对象进行更新,它将再次创建一个新对象。
你可以这样通过
.update({'name': oneController.text, 'birth': twoContorller.text, 'email': threeController.text});
或者,您也可以使用set( setOptions: SetOptions(merge:true))
这将仅更新文档中已更改的字段。
推荐阅读
- nginx - 在 AWS ALB 上使用多个域在 NGINX 级别阻止 IP
- php - 将“INSERT”MySQL 查询转换为 Postgresql 查询
- flutter - 当我使用 google_maps_flutter 在地图中点击标记时如何获取警报框:^0.2.0 插件
- phpstorm - PhpStorm 未暂停的断点从未命中
- android - android soong 构建系统的原生代码覆盖率
- php - SQL 查询加载速度比它说的要慢
- java - 我应该改变什么来优化替换方法?
- python - 为什么局部变量会自我更新?
- php - 将 JSON 文件导入 Laravel
- jquery - 当我们在调度程序选项中设置“selectable: true”时,调度程序获得焦点它会跳转