Firestore 安全规则 - 更新一个特定字段而不为其他字段提供数据

Firestore Security Rules - Update one specific field without providing data for the other fields

我是 Firestore 的新手,它的安全规则。对于我的项目,我有一些简单的数据验证规则,如下所示:

match /users/{userId} {
    allow create, update: if
        request.resource.data.name is string &&
        request.resource.data.age is int &&
        request.resource.data.score is int;
}

目前我只在模拟器上测试过它并且它在验证数据方面工作正常,但问题是对于每个查询我必须为规则中提到的所有 fields/keys 提供数据.例如,如果我想更新用户的name,我还需要提供agescore数据。

我应该如何构建我的规则,以便只更新一个特定字段而不为其他字段提供数据?

您可以使用 get() 获取字段并设置默认值,如果它不存在,如下所示:

match /users/{userId} {
  allow create, update: if
    request.resource.data.get("name", "") is string &&
    request.resource.data.get("age", 0) is int &&
    request.resource.data.get("score", 0) is int;
  }
}

检查文档中的 enforcing types for optional fields 部分。

request.resource.data 变量包含写入操作后存在的数据(如果成功),因此除非您的代码覆盖所有字段,否则它应该包含您现有文档的合并字段正在更新 update() 调用中指定的字段。

如果 playground 规则不遵循这些规则,那可能是 playground 中的错误。我建议(也)使用实际代码进行测试,因为我非常确定 update 调用没有错误(因为它会导致相当多的支持调用)。