首页 > 解决方案 > 如何通过安全规则禁止更新 Firestore 文档中的特定字段?

问题描述

我有一个事件文档,其中包含标题、位置、容量、坐标等字段。我想设置允许更新文档的安全规则,但如果用户尝试更改容量字段,则会拒绝请求

那么如何编写这样的安全规则呢?我可以这样做吗?

service cloud.firestore {
    function admin() {
        return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
    }
    match /databases/{database}/documents {
        match /events/{eventId} {

              allow update: if // (allow if user not trying to update capacity field) ???
        }
    }
}

标签: firebasegoogle-cloud-firestorefirebase-security

解决方案


将请求的文档更新的内容与现有内容进行比较,以确保它没有改变:

allow update: if request.resource.data.capacity == resource.data.capacity;

request.resource是传入请求的文档。 资源是现有数据。


推荐阅读