如何用Firebase Firestore安全规则的count()限制文档创建?附故障代码
Firestore安全规则中用count()限制用户文档创建数量
你当前代码的问题在于误用了get()方法——get()只能获取单个指定文档,没法搭配where条件做集合范围的查询。要统计用户已创建的文档数量,得用query()来构建集合查询,再调用count()方法。
修正后的规则代码如下:
match /doc/{docId} { allow read: if resource.data.publicAccess == true || (request.auth != null && request.auth.uid == resource.data.createdBy); allow write: if request.auth != null && request.auth.uid == resource.data.createdBy; allow create: if request.auth != null && request.auth.uid == request.resource.data.createdBy && // 正确构建查询并统计用户已创建的文档数 query(/databases/$(database)/documents/doc) .where("createdBy", "==", request.auth.uid) .count() < 10; }
额外注意事项
- 要确保
doc集合里的文档都正确设置了createdBy字段,且字段值为用户的UID字符串,否则查询统计会出错。 - 安全规则中的
count()操作会消耗Firestore的查询配额,若你的应用有高频创建文档的场景,可能会触发配额限制。这种情况下更推荐用计数器文档方案:- 新建一个
userCounters集合,每个用户对应一个以UID命名的文档,里面存docCount字段记录该用户创建的文档数。 - 修改规则如下:
// 限制doc集合的创建操作 match /doc/{docId} { allow read: if resource.data.publicAccess == true || (request.auth != null && request.auth.uid == resource.data.createdBy); allow write: if request.auth != null && request.auth.uid == resource.data.createdBy; allow create: if request.auth != null && request.auth.uid == request.resource.data.createdBy && get(/databases/$(database)/documents/userCounters/$(request.auth.uid)).data.docCount < 10; } // 确保只有用户自己能操作计数器 match /userCounters/{uid} { allow read, write: if request.auth != null && request.auth.uid == uid; }- 客户端创建文档时,先通过原子递增操作更新
userCounters里的docCount,再创建doc集合的文档,这样性能更稳定,也能避免配额问题。
- 新建一个
内容的提问来源于stack exchange,提问作者alberto sansegundo
相关产品推荐
相关产品推荐

