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

能否在Cloud Firestore规则中使用模板字符串变量实现动态字段校验?

Firestore Rules: Accessing Dynamic Field Keys for Validation

Great question! You're spot on that the $(something) template syntax only works when defining document paths in Firestore Security Rules—it won't let you dynamically reference field names using that syntax. But don't worry, there's a simple workaround using bracket notation that does exactly what you need.

The Solution

Instead of trying to use the template syntax for field access, use square brackets to dynamically reference the field key using the user's UID:

allow update: if request.auth != null && 
               request.auth.uid == resource.data.players[request.auth.uid].id;

How It Works

In Firestore Rules, when you need to access an object's property using a variable (like request.auth.uid here), bracket notation [] replaces the dot notation. This lets you:

  • Check that the user is authenticated (request.auth != null—always a good practice to avoid null errors)
  • Dynamically target the specific entry in the players object using the user's UID as the key
  • Validate that the id field inside that entry matches the user's authenticated UID

Extra Safety Check

To avoid errors if the user's UID isn't present in the players object, add an existence check first:

allow update: if request.auth != null && 
               request.auth.uid in resource.data.players &&
               request.auth.uid == resource.data.players[request.auth.uid].id;

This ensures the rule only proceeds to validate the id field if the user's entry actually exists in the players object, preventing unexpected rule failures.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:46:19