How can I provide the maximum number of children in a node?

How can I ensure the maximum number of node children using a security rule?

/bar/customers/$customer/drinks_ordered

There should not be more than fifteen children.

+5
source share
1 answer

It may seem that you can use a numeric identifier for the ordered drinks, and then try something like this; it will fail, since the identifier is a string:

"$customer_id": {
    "drinks_ordered": {
       "$drink_id": {
          ".validate": "$drink_id > 0 && $drink_id < 16" // error
       }
    }
}

Instead, you can use the counter and check the counter for 1-15, and then check the drink identifier corresponding to 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 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

, , 4 ( , ), .

, :)

+4

All Articles