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

如何用Firestore规则验证文档内posts数组的字段合法性?

可以通过Firestore规则实现需求,无需创建子集合

完全不需要创建独立的posts子集合,你可以通过Firestore安全规则严格限制posts数组中每个元素的结构,确保仅包含title和body字段。

核心规则思路

  • 验证更新后的posts字段是数组类型
  • 遍历数组中的每个元素,确保每个元素的键仅包含title和body
  • 可选:验证title和body的类型(比如必须是字符串,匹配你的示例结构)

具体规则示例

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /profile/{userId} {
      allow update: if 
        // 确保posts是数组
        request.resource.data.posts is list &&
        // 检查数组中每个post的结构
        every(post in request.resource.data.posts) {
          // 仅允许title和body两个字段
          post.keys().hasOnly(['title', 'body']) &&
          // 验证字段类型为字符串(可根据需求调整)
          post.title is string &&
          post.body is string
        };
    }
  }
}

规则说明

  • 不管是替换整个posts数组,还是用arrayUnion添加单个新post,这个规则都会生效——因为request.resource.data.posts指向更新后的完整数组,所有元素都必须符合结构要求。
  • 如果需要允许其他字段,只需要修改hasOnly里的数组;如果不需要类型验证,可以去掉post.title is string和post.body is string这两行。

内容的提问来源于stack exchange,提问作者Lars Flieger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 09:05:58