2016-08-14 54 views
2

我是一个新的firebase,我想知道如何找出有关hasChildren()的问题DataDataSnapshot以及如何验证数据将被创建。分贝避免创建额外的孩子Firebase

样品:

{ 
    "visitors" : { 

    "-KP4BiB4c-7BwHwdsfuK" : { 
     "mail" : "[email protected]", 
     "name" : "aaa", 
    } 
    ..... 
} 

规则:

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

    } 
} 

据我知道如果我想创建的数据,数据字段必须具有相同的名称,以通过规则验证。 例如: 如果我为每个“名称”更改“名称”,并尝试用他们的子元素创建一个新节点,则规则的工作原理我可以理解。 我想知道如果我手动添加一个新的字段来创建会发生什么?

例如:

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

结果是:

"visitors" : { 
    "-KP4BiB4c-7BwHwdsfuK" : { 
     "mail" : "[email protected]", 
     "name" : "juan", 
    "extra1":222, 
     "extra2":333 
    } 
} 

所以我的问题是如何避免创建每个节点额外的孩子的?我认为规则做到了。

在此先感谢。

回答

6

您的验证规则说你的文章必须有ATLEAST那些孩子,而不是只那些孩子。 为了确保没有其他子女可以加入你有以下添加到您的规则:

{ 
    "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 } 
     } 
    } 
    } 
} 

就拿另一个例子看看here