Search code examples
firebase-realtime-databasefirebase-security

Firebase Realtime Database - Write if user is not in the User ID list OR if it is then if the newData.Val() is less than the data.Val()


I want to

  • if a user is not in the userID list to let him write his time( this only happens the first time - regardless his score)
  • after that if his new time is less than his current time let him write to the database.

is there a way to do this? Can anyone help me ?

Unfortunately i cannot make it work. I have only succeed to the part to check the old value and the new value. This works But ONLY this if the user is ALREADY registered in the database.

I also tried to add the !data.exists but it is not working .

Below my rules

{
  "rules": {
    ".read": true,
      "Users" : {
           "3X3": {
             "$userID": {
               ".write": "data.child('time').val() > newData.child('time').val()"
             }
         }
      }
  }
}

Solution

  • I think you're looking for:

    {
      "rules": {
        ".read": true,
          "Users" : {
               "3X3": {
                 "$userID": {
                   ".write": "
                     !data.exists() || // 👈
                     data.child('time').val() > newData.child('time').val()
                   "
                 }
             }
          }
      }
    }
    

    Also see the Firebase documentation on new vs existing data in security rules.