Firestore安全规则报错:调用get函数时路径格式错误
问题定位与解决办法
问题原因
- Firestore路径结构违规:Firestore要求数据路径必须严格遵循「集合→文档→集合→文档」的交替层级。你规则中
get()请求的路径/databases/(default)/documents/cTgy9W6Zt2dShSgqig2ToeYLEzt2/users/abc@example.com存在结构错误:cTgy9W6Zt2dShSgqig2ToeYLEzt2是顶层集合,users被直接作为子集合放在其下,而Firestore不允许集合直接包含子集合——子集合必须依附于某个文档。 - 路径解析时因层级错误被判定为「格式非法」,而非文档不存在。
解决办法
方案1:调整数据结构(推荐)
修改数据层级,让子集合依附于文档:
- 在
cTgy9W6Zt2dShSgqig2ToeYLEzt2集合下创建一个文档(比如用用户UID作为文档ID,或固定ID如metadata)。 - 将
users子集合放在该文档之下。
对应的规则修改为:
service cloud.firestore { match /databases/{database}/documents { match /admins/{document=**} { allow read, write: if true; } match /{userId}/{document=**} { allow read, write: if request.auth.uid == userId || get(/databases/$(database)/documents/$(userId)/metadata/users/$(request.auth.token.email)).exists; } } }
方案2:重构顶层集合结构
将users设为顶层集合,文档ID用用户邮箱,简化路径逻辑:
service cloud.firestore { match /databases/{database}/documents { match /admins/{document=**} { allow read, write: if true; } match /{userId}/{document=**} { allow read, write: if request.auth.uid == userId || get(/databases/$(database)/documents/users/$(request.auth.token.email)).exists; } } }
方案3:使用path()函数构建路径(避免字符串拼接问题)
在规则中用path()函数动态构建路径,降低格式错误风险:
service cloud.firestore { match /databases/{database}/documents { match /admins/{document=**} { allow read, write: if true; } match /{userId}/{document=**} { allow read, write: if request.auth.uid == userId || get(path(["databases", database, "documents", userId, "metadata", "users", request.auth.token.email])).exists; } } }
额外验证点
- 确认
request.auth.token.email不为空:可以在规则中添加非空判断,避免因邮箱缺失导致的路径错误,比如:request.auth.token.email != null && get(...).exists - 检查目标文档是否实际存在:路径修复后,若仍报错,需确认
users子集合下是否存在对应邮箱的文档。
内容的提问来源于stack exchange,提问作者Ishant Singh
相关产品推荐
相关产品推荐

