0

I want to upload image information in the database where photoJson is unique. Before inserting I want to check if it already exists in the database. So I wrote this rule. When in-app I upload info it is duplicating data. I know the question like this already exist but I tested the solution and it's not working.

{
"rules": {
"wallpapers" :{
  ".read": true,
    ".write" : true,
    "$wallpaper":{
      "photoJson": {
        //Checking if same wall already exists
        ".validate": "!root.child('wallpapers').child(newData.val()).exists()",
      },
      "url": {
        ".validate": "newData.isString()"
      },
      "thumbUrl": {
        ".validate": "newData.isString()"
      },
      "likes": {
        ".validate": "newData.isNumber()"
      },
      "dislikes": {
        ".validate": "newData.isNumber()"
      },
      "favorites": {
        ".validate": "newData.isNumber()"
      }
      }
  }
}
}
Ankur Gupta
  • 410
  • 1
  • 6
  • 17
  • There is no way in security rules of a certain value already exists in a collection of nodes. For examples, see https://stackoverflow.com/q/35243492, https://stackoverflow.com/q/24820597, – Frank van Puffelen Jun 23 '17 at 21:39
  • @FrankvanPuffelen Then what does `".validate": "!root.child('wallpapers').child(newData.val()).exists()",` statement is doing actually? – Ankur Gupta Jun 24 '17 at 09:30
  • It check if a child with the name `newData.val()` exists in the `wallpapers` location. – Frank van Puffelen Jun 24 '17 at 17:50

1 Answers1

1

The solution is in app logic, not Firebase rules. Reference

ref.child("-JlvccKbEAyoLL9dc9_v").addListenerForSingleValueEvent(new 
    ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot snapshot) {
          if (!snapshot.exists()) {
              // TODO: handle the case where the data does not yet exist
          }
   }

  @Override
  public void onCancelled(FirebaseError firebaseError) { }
});
Ankur Gupta
  • 410
  • 1
  • 6
  • 17
  • This just checks of `-JlvccKbEAyoLL9dc9_v` already exists under `ref`. Since keys generated by `push()` are statistically guaranteed to be unique, you don't have to check for this. – Frank van Puffelen Jun 24 '17 at 17:51