Reputation: 1351
I have read Firebase documentation about rules and how to validate new data that is written in the database. There is a line where I don't understand a certain thing does.
Below is the code of firebase rules from Firebase Documentation.
{
"rules": {
".write": true,
"widget": {rules)
".validate": "newData.hasChildren(['color', 'size'])",
"size": {
".validate": "newData.isNumber() &&
newData.val() >= 0 &&
newData.val() <= 99"
},
"color": {
// the value of "color" must exist as a key in our mythical
// /valid_colors/ index
".validate": "root.child('valid_colors/' + newData.val()).exists()"
}
}
}
}
".validate": "root.child('valid_colors/' + newData.val()).exists()"
is where I don't understand what it is and what it does.
root.child
? Is it used to access the child of the color?newData.val()).exists()
? What exists()
used for?Upvotes: 0
Views: 1387
Reputation: 13033
When you use "root" it goes back all the way to the top. Imagine a database like this:
Database:
-users
-uid's
-username
-valid colors
-blue
-red
When you say root.child("users")
, you go into the map which contains the users.
And when you say root.child("valid colors/blue")
will go look into that submap of valid colors.
Exists check if it exists in the database. newData
stands for the data you want to enter. If you want to enter "green", it will fail. This is because if your JSON looks like this:
"color" : green
newData.val() = green
Does it exists in your database? No, not in the example provided. That is why it will fail. The color blue exists in your database. When you enter that as your new data, it will pass the rule.
Upvotes: 2