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

如何为Firestore集合组查询配置正确的安全规则?

Firestore集合组查询权限问题解决方法

问题原因

你之前的规则写法不匹配集合组查询的要求。集合组查询是跨所有父集合的同名子集合,需要用**任意路径通配符{path=**}**匹配所有包含list子集合的父路径,而你之前的规则都是限定在maincollection下的特定层级,Firestore无法识别为集合组的权限规则。

正确的安全规则

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // 匹配所有路径下的list集合,支持集合组查询
    match /{path=**}/list/{doc} {
      allow read: if request.auth != null;
    }
  }
}

关键说明

  • 必须指定rules_version = '2':规则版本1不支持集合组查询的通配符匹配逻辑,只有版本2才兼容这种写法。
  • 确保用户登录状态:request.auth != null要求用户必须通过Firebase Auth登录才能访问数据,如果业务允许未登录访问,可移除该条件,但不建议这么做。
  • 更严格的权限控制(可选):如果只允许用户访问自己的list数据,需要同步修改规则和查询:
    • 规则调整:
      match /maincollection/{userId}/list/{doc} {
        allow read: if request.auth.uid == userId;
      }
      
    • 查询添加过滤条件:
      const searchQuery = query(
        MainCollection,
        where("destination", "==", itinerary.destination),
        where("userId", "==", auth.currentUser.uid) // 过滤当前用户的数据
      );
      

内容的提问来源于stack exchange,提问作者D.Hodges

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:04:58