2016-08-14 53 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