【问题标题】:Check if same data exist in database by firebase rules通过firebase规则检查数据库中是否存在相同的数据
【发布时间】:2017-06-23 20:52:09
【问题描述】:

我想上传photoJson唯一的数据库中的图像信息。在插入之前,我想检查它是否已经存在于数据库中。所以我写了这条规则。当我在应用内上传信息时,它正在复制数据。我知道这样的问题已经存在,但我测试了解决方案,但它不起作用。

{
"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()"
      }
      }
  }
}
}

【问题讨论】:

  • 没有办法在节点集合中已经存在某个值的安全规则。例如,请参阅stackoverflow.com/q/35243492stackoverflow.com/q/24820597
  • @FrankvanPuffelen 那么".validate": "!root.child('wallpapers').child(newData.val()).exists()", 语句实际上在做什么?
  • 它检查名称为newData.val() 的孩子是否存在于wallpapers 位置。

标签: android firebase firebase-realtime-database


【解决方案1】:

解决方案在于应用逻辑,而不是 Firebase 规则。 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) { }
});

【讨论】:

  • 这只是检查-JlvccKbEAyoLL9dc9_v 已经存在于ref 下。由于push() 生成的密钥在统计上保证是唯一的,因此您不必对此进行检查。
猜你喜欢
  • 1970-01-01
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 2020-11-02
  • 1970-01-01
  • 2016-11-07
  • 2018-08-26
相关资源
最近更新 更多