如何为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
相关产品推荐
相关产品推荐

