Firebase rules and validations for update existing data

风格不统一 提交于 2019-12-11 05:20:20

问题


I have a data structure as following:

    {
     "users" : {
      "31J59dq1clZ3inHMzoopiigsEg63" : [ {
       "name" : "Lanchana",
       "timestamp" : 1516916245423,
       "uid" : "31J59dq1clZ3inHMzoopiigsEg63",
       "userEmail" : "*****@gmail.com",
       "total-stars" : 123
        } ]
      }
    }

and fire rules as following:

    {
      "rules": {
        "users": {
          "$uid": {
            ".read": "$uid === auth.uid && auth != null",
            ".write": "!data.exists() || data.child('uid').val() == 
                       auth.uid && auth != null",
                }
         }
       }
    }

I can add new data successfully but I cannot make any updates to the existing one. for ex: If I want to update only total-stars of a particular user based on the uid, how can I specify write and validation rules?


回答1:


Your data structure seems to have a layer 0 that is missing from the rules. If that layer indeed exists in your actual JSON, you'll want to have it in your rules too:

{
  "rules": {
    "users": {
      "$uid": {
        "$postid": {
          ".read": "$uid === auth.uid && auth != null",
          ".write": "!data.exists() || data.child('uid').val() == 
                   auth.uid && auth != null",
        }
     }
   }
}

I called the layer $postid here. You may want to use a name that better reflects what the layer represents.



来源:https://stackoverflow.com/questions/48467190/firebase-rules-and-validations-for-update-existing-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!