首页 > 解决方案 > 正在创建新文档而不是更新

问题描述

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;

我不确定如何最好地解决这个问题。

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


是的,使用set()将覆盖 Firestore 中已经存在的所有数据。

是的,使用update是要走的路,但请记住不要调用.toJson()整个对象,因为更新只需要需要更新的字段。因此,如果您使用整个对象进行更新,它将再次创建一个新对象。

你可以这样通过

.update({'name': oneController.text, 'birth': twoContorller.text, 'email': threeController.text});

或者,您也可以使用set( setOptions: SetOptions(merge:true))这将仅更新文档中已更改的字段。


推荐阅读