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

Firestore安全规则出现空值错误,请求排查解决

解决Firestore安全规则中的Null值错误

问题定位

你遇到的第11行空值错误,核心原因有两点:

  1. 冗余的get()调用:规则里重复调用get(/databases/$(database)/documents/clarity/$(documentId))完全没必要——当前匹配的就是/clarity/{documentId}文档,直接用resource对象就能获取当前文档数据,额外的get()不仅多余,还可能在模拟调试时因场景触发空值。
  2. 字段名大小写不匹配:你在users集合规则中用的是user_id(下划线命名),但clarity规则中用的是userId(驼峰命名),如果数据库里clarity文档的实际字段名是user_id,会导致resource.data.userId返回null,触发错误。

修正后的安全规则

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // 用户集合权限:仅认证用户且uid匹配文档user_id
    match /users/{documentId} {
      allow read, update, delete: if isSignedIn() && request.auth.uid == resource.data.user_id;
    }
    
    // Clarity集合权限:仅认证用户且uid匹配文档对应字段(注意字段名要和数据库一致)
    match /clarity/{documentId} {
      allow read, update, delete: if isSignedIn() && request.auth.uid == resource.data.userId;
      allow create: if isSignedIn();
    }
  }
}

function isSignedIn() {
  return request.auth != null;
}

调试必做检查

  • 核对数据库字段名:如果clarity文档实际字段是user_id,把规则里的userId改成user_id。
  • 模拟器设置:必须勾选“已认证”,输入与目标文档userId(或user_id)一致的uid,且选择已存在的clarity文档路径进行模拟。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:10:01