问题
I have a bunch of documents that contain a few fields each. How can I write rules that only apply to a specific field in each document?
For example, if my documents looked like this:
{
"displayName": "John Doe", // read and write
"accessLevel": 3 // read only
}
How could I make it so that you can
- Read display name and access level
- Write to the display name
- Not write to the access level
I've gone through a lot of videos and Firestore docs and haven't found anything that shows how you would exercise this per-field control.
回答1:
What you're looking for is to make a field non-modifiable. You do that by checking in your rules that the value of the field is the same after the request as before it.
I have a simple helper function for this in my rules:
function isUnmodified(key) {
return request.resource.data[key] == resource.data[key]
}
I then call this function from within my write
(or create
and update
) rules:
allow update: if isAdmin() || isUnmodified('name');
So in my example above, any admin (as determined by my isAdmin
function) can modify the name field, but other users can't.
来源:https://stackoverflow.com/questions/58423627/per-field-rules-in-firestore-security-rules