如何使用安全规则强制执行节点的最大子节点数?
/bar/customers/$customer/drinks_ordered
不应超过十五个孩子。
答案 0 :(得分:5)
看起来您可以使用数字ID来订购饮品然后尝试这样的事情;它会失败,因为ID是一个字符串:
"$customer_id": {
"drinks_ordered": {
"$drink_id": {
".validate": "$drink_id > 0 && $drink_id < 16" // error
}
}
}
相反,您可以使用计数器并将计数器验证为1-15,然后验证饮品ID是否与计数器匹配。
"$customer_id": {
"counter": {
// counter can only be incremented by 1 each time, must be a number
// and must be <= 15
".validate": "newData.isNumber() && newData.val() > 0 && newData.val() <= 15 && ((!data.exists() && newData.val() === 1) || (newData.val() === data.val()+1))"
},
"drinks_ordered": {
// new record's ID must match the incremented counter
"$drink_id": {
// use .val()+'' because $drink_id is a string and Firebase always uses ===!
".validate": "root.child('bar/customers/'+$customer_id+'/counter').val()+'' == $drink_id"
}
}
}
当然,你的饮料看起来像这样:
/bar/customers/george_thorogood/counter/3
/bar/customers/george_thorogood/drinks_ordered/1/burbon
/bar/customers/george_thorogood/drinks_ordered/2/scotch
/bar/customers/george_thorogood/drinks_ordered/3/beer
现在,在客户端添加另一种饮料之前,他们必须将计数器设置为4(这是唯一可以设置的饮品),然后添加具有相同ID的饮品。
有点迂回,但确实有效:)