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

Firebase新手求助:如何编写Firestore规则实现用户仅读写自身文档

Firestore 实现用户仅读写自身文档的规则方案

常见问题排查与修正

你当前的规则未生效,大概率是以下两个原因:

  1. 集合名称不匹配:规则里的some_collection需要替换成你实际使用的集合名称(比如截图里的集合名)
  2. 文档结构或匹配逻辑不符:根据你的集合结构,分三种场景调整规则:

场景1:用户文档直接存于根集合(文档ID = 用户UID)

如果你的集合是类似users/{userId}的结构,每个文档的ID就是用户的Firebase Auth UID,使用以下规则:

service cloud.firestore {
  match /databases/{database}/documents {
    // 仅允许认证用户读写自己的文档
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

场景2:需要访问用户文档下的嵌套集合

如果用户文档下还有子集合(比如users/{userId}/posts/{postId}),要允许用户读写自己所有嵌套内容,用通配符匹配:

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/{documents=**} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

场景3:文档ID不等于UID,但文档内有userId字段

如果你的文档ID不是用户UID,但每个文档里存储了userId字段(对应用户的Auth UID),规则要检查文档内的字段:

service cloud.firestore {
  match /databases/{database}/documents {
    match /your_collection/{docId} {
      allow read, write: if request.auth != null && resource.data.userId == request.auth.uid;
    }
  }
}

测试验证

修改规则后,用Firebase控制台的规则模拟器测试:

  • 选择认证用户,输入对应UID
  • 模拟读/写操作,确认规则是否正确拦截非授权访问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:33:18