简体   繁体   中英

Firebase Database Rules - how not to overwrite existing data

I have a problem writing the "WRITE" rule in my Firebase Database. I have a node "drink_database" and inside of it, I have a list of barcodes of those drinks. This can be seen from the code

{
  "drink_database": {
    "8888": {
      "barcode": "8888",
      "drink_volume": "1234",
      "image": "https://firebasestorage.googleapis.com/v0/b/popbar-664cd.appspot.com/o/drinks_images%2F8888?alt=media&token=72886b8c-f0fb-4729-a125-848ad2a48321",
      "name": "sjsnj"
    },
    "1234568": {
      "barcode": "1234568",
      "drink_volume": "7879",
      "image": "https://firebasestorage.googleapis.com/v0/b/popbar-664cd.appspot.com/o/drinks_images%2F1234568?alt=media&token=2d6dcc56-7a29-4551-8c32-c9b2765c436d",
      "name": "vodka"
    }
  }
}

Now, the users of the app will be able to upload drinks to the database, BUT ONLY if the barcode of that drink DOES NOT exist in the database. So, from the example above, if user's drink has the barcode "8888" and the user tries to upload it to the Firebase, I don't want this data to be overwritten with user's data. Also, I want only authenticated users to be able to write data. Can somebody help with the rules?

{
  "rules": {

    "drink_database": {
      ".read": "auth != null",
      ".write": "?????"
    }
  }
}

In your case where only authenticated users can create (and not update or delete) data the rules are simple:

{
  "rules": {    
    "drink_database": {
      ".read": "auth != null",
      //Using a wildcard for the barcodes
      "$barcode": {
        //Only authenticated users can write when there is no existing data
        ".write": "auth != null && !data.exists()"
      }
    }
  }
}

For more information and examples I suggest you take some time and read through the firebase docs .

If you also want to be able to delete data you can change your write rule to this:

".write": "auth != null && (!data.exists() || !newData.exists())"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM