Avoid create extra childs Firebase

混江龙づ霸主 提交于 2019-12-10 10:16:58

问题


Im a new in firebase and I wish to know how to figure out a question regarding to hasChildren() RuleDataSnapshot and how validates the data will be created.

Sample of db :

 {
  "visitors" : {

   "-KP4BiB4c-7BwHwdsfuK" : {
      "mail" : "aaa@mail.com",
      "name" : "aaa",
    }
    .....
}

Rules :

{
    "rules": {
        "visitors": {
            ".read": "auth != null",
            ".write": "auth.uid != null",
                "$unique-id": {
                    ".read": "auth != null ",
                    ".write": "auth != null",
                    ".validate": "newData.hasChildren(['name','mail'])",
            }
        }

    }
}

As far I know if I want to create data, the data fields must have the same names to pass the rule validation. For example : If I change "name" per "names" and I try to create a new node with their childs the rule works as far I could understand. I wondering ¿ what happend if I add manually a new fields to create ?

For example :

//Add extra fields which are not actually present
 var data = {name : "xxx",mail:"xxx@mail.com",extra1:222,extra:333};
 firebase.database().ref('visitors/').push(data);

The result is :

  "visitors" : {
  "-KP4BiB4c-7BwHwdsfuK" : {
      "mail" : "aaa@mail.com",
      "name" : "juan",
     "extra1":222,
      "extra2":333
    }
}

So my question is how to avoid create extra childs per node ? I supposed the rule did it.

Thanks in advance.


回答1:


Your validate rule says your post must have atleast those children and not only those children. To ensure no other children can be added you have to add the following to your rules:

{
  "rules": {
    "visitors": {
        ".read": "auth != null",
        ".write": "auth.uid != null",
        "$unique-id": {
            ".read": "auth != null ",
            ".write": "auth != null",
            //This line says the new data must have ATLEAST these children
            ".validate": "newData.hasChildren(['name','mail'])",   
            //You can add individual validation for name and mail here     
            "name": { ".validate": true },
            "mail": { ".validate": true },
            //This rule prevents validation of data with more child than defined in the 2 lines above (or more if you specify more children)
            "$other": { ".validate": false }
        }
    }
  }
}

Take a look here for another example.



来源:https://stackoverflow.com/questions/38944544/avoid-create-extra-childs-firebase

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