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

Firestore安全规则配置:限制用户最多创建10个文档

Firestore安全规则V2实现用户文档数量限制

核心实现思路

通过Firestore安全规则V2的集合查询统计能力,在用户创建新文档前,校验其已拥有的对应类型文档数量是否超过10个阈值,以此禁止超额创建。同时保留前端限制作为体验优化,后端规则作为最终安全屏障。

完整安全规则代码

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // 通用计数校验函数,可复用给不同集合
    function isUnderDocumentLimit(collectionName, maxCount) {
      // 统计当前用户在目标集合下的文档总数
      let userDocCount = get(/databases/$(database)/documents/$(collectionName)).where('uid', '==', request.auth.uid).size();
      return userDocCount < maxCount;
    }

    // 追踪器集合规则
    match /trackers/{trackerId} {
      allow create: if request.auth != null && isUnderDocumentLimit('trackers', 10);
      allow read, update, delete: if request.auth != null && resource.data.uid == request.auth.uid;
    }

    // 博客文章集合规则
    match /blog-posts/{postId} {
      allow create: if request.auth != null && isUnderDocumentLimit('blog-posts', 10);
      allow read, update, delete: if request.auth != null && resource.data.uid == request.auth.uid;
    }

    // 视频集合规则
    match /videos/{videoId} {
      allow create: if request.auth != null && isUnderDocumentLimit('videos', 10);
      allow read, update, delete: if request.auth != null && resource.data.uid == request.auth.uid;
    }
  }
}

关键细节说明

  • 规则基于V2版本编写,利用get()方法结合.where()和.size()实现用户文档数量统计,这是V1版本不支持的能力。
  • 提取通用函数isUnderDocumentLimit,可快速为不同集合配置数量限制,避免重复代码。
  • 创建操作必须先校验用户登录状态,再校验数量阈值,确保只有合法用户且未超额时才能创建文档。
  • 读写更新规则限制用户仅能操作自己的文档,保证数据隔离性。

额外注意点

  • 前端的数量限制仍需保留,作为第一重拦截减少无效请求,提升用户体验;后端规则是防止恶意绕过前端限制的最终保障。
  • 单用户小数量(10个)的统计操作对规则评估性能影响极小,无需担心资源消耗问题。

内容的提问来源于stack exchange,提问作者Sebastian K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:30:21