ImNeos
ImNeos

Reputation: 567

Firebase rules setValue only if a child exist

I'm trying to use rules but it's not working.

Here is the structure :

enter image description here

I have this command : DeleteItemFromListRef.child("List").child(obj.getsEventID()).child(ID).child("check").setValue(false);

But I want to set the value to "false" only if the child (key) exists so that if the item is deleted, I will not simply have that :

enter image description here

Here is my rules :

 "List": {
    "$listID" : {
      "$key": {
        "check" : {
      ".write":"data.child('List').child($listID).child($key).child('key').exists()"
    }
  }
}

}

But still, if the child key is empty, it still uploads the data like this :

enter image description here

if anyone can help, would be nice

EDIT 2: here are much simpler rules

"rules": {






           "List": {
            "$listID" : {
               "$key": {
                 "check" : {  
".read":"auth.uid != null", 
".write":"auth.uid != null", 
".validate":"data.parent().child('key').exists()"

}
}}}}}

+COMMENTS :

So I always update the item with a map if I add a new one, but if I change only the child "check" I use the "setValue" method and want the setValue to be done only if the item is already there (== child key already exist)

Upvotes: 2

Views: 1770

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 600141

If you only want to allow writing checked if its sibling property key exists, you can do:

"List": {
    "$listID" : {
        "$key": {
            "check" : {
                ".validate":"data.parent().child('key').exists()"
            }
        }
    }
}

Update Since you're having trouble making this work, I just tested it in a very simple setup. Under /55431756 in my database, I have this JSON:

{
  "has_key" : {
    "key" : "value"
  }
}

So it's a single key has_key that has a key. Now I ran two simulations: one trying to write to has_key.

Writing to has_key succeeds, since has_key/key exists:

Writing to <code>has_key</code> is allowed

Writing to no_key is denied, since there is no no_key/key child:

Writing to <code>no_key</code> is denied

Upvotes: 1

Saurav Kumar
Saurav Kumar

Reputation: 970

Well, you can also first check whether the child exists and upon true perform the above command.

Upvotes: 2

Related Questions