You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore已存在文档却返回不存在?求解决方法

问题:Firestore无法找到已存在的文档

我手动在Firestore集合中添加了一个文档,将当前用户ID复制粘贴作为文档ID,并添加了字段及对应值,但检索时Firestore返回文档不存在。

相关代码与信息

集合引用定义

final _grocerData = FirebaseFirestore.instance.collection('grocers/{abc1}/fruits/{abc2}/apples/');

查询方法代码

Future<void> getData() async {
  final document = await _grocerData.doc(_auth.currentUser!.uid).get();
  if (document.exists) {
    print('Hooray!  The document was found!');
  } else {
    print('Boohoo!  Firestore cannot find the specified document');
    print('The current-user\'s ID: ${_auth.currentUser!.uid}');
  }
}

日志输出

I/flutter (20975): Boohoo!  Firestore cannot find the specified document
I/flutter (20975): The current-user's ID: cGr1Fh8d9PgI9VJ2UzbeBVmRbhk2

我已确认文档存在且路径正确,但Firestore仍判定文档不存在,请问原因是什么,该如何解决?


原因分析

你的集合引用路径中使用了{abc1}和{abc2}作为占位符,但Firestore不会自动解析这类占位符,它会把整个字符串grocers/{abc1}/fruits/{abc2}/apples/当作实际的集合路径。这意味着代码当前指向的是一个名为{abc1}的文档下的fruits集合,再找名为{abc2}的文档下的apples集合,和你手动创建文档时的真实路径完全不符,所以无法找到目标文档。

解决方法

需要将集合路径中的占位符替换为实际的文档ID(即你手动创建文档时,grocers下的真实文档ID,以及fruits下的真实文档ID)。

固定路径写法

如果路径是固定的,直接替换占位符为真实ID即可:

final _grocerData = FirebaseFirestore.instance.collection('grocers/真实abc1文档ID/fruits/真实abc2文档ID/apples/');

动态路径写法

如果这些ID是动态获取的(比如从其他数据或用户输入中得到),可以用字符串插值生成路径:

// 假设这两个是动态获取的真实ID变量
String abc1RealId = "实际的abc1文档ID";
String abc2RealId = "实际的abc2文档ID";
final _grocerData = FirebaseFirestore.instance.collection('grocers/$abc1RealId/fruits/$abc2RealId/apples/');

修改完成后再调用getData()方法,就能正确匹配到目标文档。


内容的提问来源于stack exchange,提问作者mathems32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:03:21