简体   繁体   中英

Controlling data-update on Firebase

I am using Firebase for a small iOS project and I wonder if the following is possible.

Under a given node "myNode_123" I store data records; each record having the shape below:

[fieldStr: "ABC_xyz", fieldNum: 678]

A record is in fact a subnode.

Now my question is about updating the data, for already existing records.

Someone should be allowed to update a data record only if the new value for fieldNum is higher than the one already there. And in any case the value for fieldStr should stay as it is.

I have already written some rules to make sure fieldNum is fullfilling my request. But I still have the issue of fieldStr having the risk of being changed.

Here are my rules:

{
  "rules": {
    ".read": true,
    //".write": true
    "myNode_123": {
        "$Record": {
            // Ensure that we are either creating a new record not yet existing,
            // or that we are only updating for a higher fieldNum.
           ".write": "(!root.child('myNode_123/'+$Record).exists()) ||
           (root.child('myNode_123/'+$Record).exists() && (newData.child('fieldNum').val() > data.child('fieldNum').val()))"
        }
    }
  }
}

The control of fieldNum is working as I wish. But it is still possible to change fieldStr, which I do not want.

Any advice from a Firebase expert?

Add this under $Record.

{
  "rules": {
    ".read": true,
    //".write": true
    "myNode_123": {
      "$Record": {
         // Ensure that we are either creating a new record not yet existing,
         // or that we are only updating for a higher fieldNum.
        ".write": "!data.exists() || newData.child('fieldNum').val() > data.child('fieldNum').val()",
        "fieldStr": {
          ".validate": "!data.exists() || data.val() == newData.val()"
        }
      }
    }
  }
}

The !data.exists() will make sure only new data can be written to this location. And data.val() == newData.val() will add an exception to allow writes when the new data is the same as the old data, just in case you want to write the entire object to the Database and include the fieldStr.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM