如果数据存在,如何禁止重写数据

How to forbid rewriting data if it exists

授权后我在table"users"添加用户。此外,我将向该用户添加一些我不想被覆盖的值。

ref.child("users").child((FIRAuth.auth()?.currentUser?.uid)!).setValue(["username": "MyName"])

规则

{
    "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
    "users": {
      ".write": "!root.child('users/'+auth.uid).exists()",
      ".read":true,
      "positive": {
        ".read": true,
          ".write":false,
      },
      "negative": {
        ".read": true,
          ".write":false,
      },
    }
  }
}

删除旧数据并放入新数据。

我想在服务器端编写规则,如果设置值已经存在,它将忽略设置值。

如果您调用 updateChildValues(),您指定的属性将被更新:

ref.child("users")
   .child((FIRAuth.auth()?.currentUser?.uid)!)
   .updateChildValues(["username": "MyName"])

参见Firebase documentation on updating specific fields

您的规则将不起作用,因为您无法取消您在树的更高级别上授予的权限。见 Firebase documentation on the cascading of permissions.

要确保用户始终具有某些属性,请在用户的节点上使用规则:

"users": {
  "$uid": {
      ".write": "newData.hasChildren(['certain', 'properties])",