我如何在一个节点中执行最大数量的子节点? [英] How can I enforce a maximum number of children in a node?
问题描述
/ bar / customers / $ 如何使用安全规则强制执行一个节点的最大子节点数? customer / drinks_ordered
不应该超过15个孩子。
看起来好像你可以使用一个数字ID作为排序的饮料,然后尝试这样的事情;它会失败,因为ID是一个字符串:
$ customer_id:{
drinks_ordered:{
$ drink_id:{
.validate:$ drink_id> 0&& $ drink_id< 16// error
}
}
}
相反,您可以使用计数器并将计数器确认为1-15,然后
$ customer_id:{
counter:{
//计数器每次只能增加1,必须是数字
//并且必须是< = 15
.validate:newData.isNumber()&& newData .val()> 0& newData.val()< = 15&&&((!data.exists()& newData.val()=== 1)||(newData .val()=== data.val()+ 1))
,
drinks_ordered:{
//新记录的ID必须匹配递增的计数器
$ drink_id:{
//使用.val()+'',因为$ drink_id是一个st戒指和Firebase总是使用===!
.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的饮料。 b
$ b
有点迂回,但它确实可以做到这一点)
How can I enforce a maximum number of children of a node using a security rule?
/bar/customers/$customer/drinks_ordered
Should not have more than fifteen children.
It might seem like you could use a numeric id for the ordered drinks and then try something like this; it will fail since the ID is a string:
"$customer_id": {
"drinks_ordered": {
"$drink_id": {
".validate": "$drink_id > 0 && $drink_id < 16" // error
}
}
}
Instead, you can use a counter and validate the counter to be 1-15, and then validate the drink ID matches the counter.
"$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"
}
}
}
Naturally, your drinks will look something like this:
/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
Now before a client could add another drink, they would have to set the counter to 4 (which is the only thing it can be set to) and then add the drink with that same ID.
A little roundabout, but it does do the job : )
这篇关于我如何在一个节点中执行最大数量的子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!