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

Firestore中使用where查询user_id匹配文档失败的问题排查

问题:Firestore带where条件查询无结果返回

我在尝试从Firestore的Contributions集合中获取所有user_id字段与用户ID匹配的文档时遇到了问题。

Firestore规则设置

// ALLOW USER TO GET THEIR OWN CONTRIBUTION
match /Contributions/{document=**} {
  allow read: if request.auth.uid != null; // && resource.data.user_id == request.auth.uid;
}

带where条件的代码及现象

使用以下Flutter函数时,仅输出用户ID,没有打印文档的border_id:

I/flutter (22264): USER ID : myuserid

Future<bool> getContributions(String userId) async {
    debugPrint("USER ID : " + userId);
    db
        .collection('Contributions')
        .where("user_id", isEqualTo: userId)
        .get()
        .then((data) => data.docs.forEach((doc) {
              debugPrint("BORDER ID : " + doc["border_id"]);
            }));
    return true;
  }

移除where条件后的正常情况

如果去掉where条件,函数就能正常输出文档的border_id:

I/flutter (22264): USER ID : myuserid

I/flutter (22264): BORDER ID : documentId // it works !

Future<bool> getContributions(String userId) async {
    debugPrint("USER ID : " + userId);
    db
        .collection('Contributions')
        //.where("user_id", isEqualTo: userId)
        .get()
        .then((data) => data.docs.forEach((doc) {
              debugPrint("BORDER ID : " + doc["border_id"]);
            }));
    return true;
  }

问题根源及提醒

经过多次尝试排查,最终发现是复制用户ID时误添加了空格。Firestore的字符串匹配是完全精确的,哪怕是一个不起眼的空格都会导致查询无法匹配到目标文档,在此提醒大家注意这类细节问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:45:16