如何用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
相关产品推荐
相关产品推荐

