casm
casm

Reputation: 43

Avoid create extra childs Firebase

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" : "[email protected]",
      "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:"[email protected]",extra1:222,extra:333};
 firebase.database().ref('visitors/').push(data);

The result is :

  "visitors" : {
  "-KP4BiB4c-7BwHwdsfuK" : {
      "mail" : "[email protected]",
      "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.

Upvotes: 3

Views: 281

Answers (1)

André Kool
André Kool

Reputation: 4978

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.

Upvotes: 7

Related Questions