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

如何用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的查询配额,若你的应用有高频创建文档的场景,可能会触发配额限制。这种情况下更推荐用计数器文档方案:
    1. 新建一个userCounters集合,每个用户对应一个以UID命名的文档,里面存docCount字段记录该用户创建的文档数。
    2. 修改规则如下:
    // 限制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;
    }
    
    1. 客户端创建文档时,先通过原子递增操作更新userCounters里的docCount,再创建doc集合的文档,这样性能更稳定,也能避免配额问题。

内容的提问来源于stack exchange,提问作者alberto sansegundo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 06:29:58