能否在Cloud Firestore规则中使用模板字符串变量实现动态字段校验?
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
playersobject using the user's UID as the key - Validate that the
idfield 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

