return 在 firebase 数据库中找不到条目时出错

return error when entry not found in firebase database

我有一个包含一些对象的数组。用户应该能够通过 moduls/ 调用所有对象,并通过 moduls/$id 调用特定对象。但是当没有模块时,数据库应该 return 一个错误,这样客户端就知道什么都没有了。

return当模块不存在时没有错误:

"moduls": {
  ".read": "true",
    "$modul": {

    }
}

return当数据不存在时出错,但当我想获取所有模块时出错:

"moduls": {
    "$modul": {
        ".read": "data.exists()",
    }
}

那么有没有办法解决这两种情况,还是最好与客户核实一下特定值是否设置为:

if(typeof modul.name === "undefined") {
    //modul not found
}

您似乎想使用安全规则来控制客户端逻辑。这可能会带来比其价值更多的问题。相反:使用客户端代码来控制客户端逻辑和安全规则,以确保您的业务规则不被违反。

如果您可以将您的业务逻辑改写成符合这些规则的内容,您的时间就会轻松得多。例如"any user can create an object, but once it is created no-one can overwrite it",变成:

"moduls": {
  "$modulId": {
    ".write": "!data.exists() && newData.exists()",
  }
}

和客户端:

function createModul(modulId) {
  var modulRef = ref.child('moduls').child(modulId);
  modulRef.once('value', function(snapshot) {
    if (snapshot.exists()) {
      console.error('Modul with '+modulId+' already exists);
    }
    else {
      modulRef.set('My new value', function(error) {
        if (error) {
          console.error('Write failed, probably somebody created '+modulId+' in the meantime')
        }
      });
    }
  }
}

现在客户端检查自己的业务逻辑,服务端保证不被违反。