Firestore更新触发NOT_FOUND错误:无待更新文档,数据未更新求助
Firestore更新触发NOT_FOUND错误的解决方法
报错信息
Stream closed with status: Status{code=NOT_FOUND, description=No document to update: projects/*/123, cause=null}
调用Firestore更新方法时出现上述错误,同时数据未完成更新,相关代码如下:
FirebaseFirestore.instance .collection('extra') .doc(widget.extraName) .update( { 'subExtra': FieldValue.arrayUnion([{'name': _subNameTextController.text}]) }, );
问题原因
update方法的核心限制是目标文档必须已存在,如果extra集合下,widget.extraName对应的文档ID不存在(拼写错误、为空、文档被删除或从未创建),就会抛出NOT_FOUND错误。
解决方案
验证文档ID正确性
先打印widget.extraName的实际值,确认是否与Firestore后台extra集合中已存在的文档ID完全匹配,排查拼写、大小写或空值问题。自动创建或更新文档
如果业务允许文档不存在时自动创建,改用set方法并开启merge: true,这样无论文档是否存在,都会合并更新指定字段:
FirebaseFirestore.instance .collection('extra') .doc(widget.extraName) .set( { 'subExtra': FieldValue.arrayUnion([{'name': _subNameTextController.text}]) }, SetOptions(merge: true), );
- 先检查再更新
若必须确保文档存在才执行更新,先通过get方法验证文档状态:
final docRef = FirebaseFirestore.instance.collection('extra').doc(widget.extraName); final docSnapshot = await docRef.get(); if (docSnapshot.exists) { await docRef.update( { 'subExtra': FieldValue.arrayUnion([{'name': _subNameTextController.text}]) }, ); } else { // 根据业务需求处理,比如提示用户文档不存在,或执行创建逻辑 }
内容的提问来源于stack exchange,提问作者Adeel Nazim
相关产品推荐
相关产品推荐

