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

Firestore单文档查询权限问题:查询不存在文档时权限错误如何解决?

问题

我有一个Firestore数据库,使用如下规则:

rules_version = '2';

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

查询批量文档时,我在查询中加入uid字段过滤就能正常通过规则验证:

try await db.collection("Stocks")
    .whereField("uid", isEqualTo: user.uid)
    .getDocuments()

但查询一个不存在的单文档时,会直接返回权限错误:

let document = try await db.collection("Stocks")
    .document(stock.id) // 该文档数据库中不存在
    .getDocument()

if document.exists {

} else {

}

请问该如何调整Firestore规则解决这个问题?

解决方案

当前规则的read权限依赖resource.data.uid,但当目标文档不存在时,resource对象为空,规则会直接判定权限不通过,导致返回错误。

你需要修改规则,允许已认证用户查询不存在的文档,同时保留对存在文档的权限校验。调整后的规则如下:

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read: if request.auth != null && (resource == null || request.auth.uid == resource.data.uid);
      allow write: if request.auth != null && request.auth.uid == resource.data.uid;
      allow create: if request.auth != null && request.auth.uid == request.resource.data.uid;
    }
  }
}

规则说明

  • resource == null 用于判断文档是否不存在,此时只要用户已认证就允许查询,这样不存在的文档会正常返回document.exists = false,而非权限错误。
  • 对于已存在的文档,依然要求request.auth.uid == resource.data.uid,确保用户只能访问自己的文档。
  • 写入和创建规则保持原有逻辑,保证用户只能操作属于自己的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 23:08:20