且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查 firebase 数据库中是否存在值

更新时间:2021-07-14 06:50:21

exists() 方法是 Firebase 查询返回的 snapshot 对象的一部分.因此请记住,您将无法避免检索数据以验证它是否存在.

The exists() method is part of the snapshot object which is returned by firebase queries. So keep in mind that you won't be able to avoid retrieving the data to verify if it exists or not.

ref.child("users").orderByChild("ID").equalTo("U1EL5623").once("value",snapshot => {
    if (snapshot.exists()){
      const userData = snapshot.val();
      console.log("exists!", userData);
    }
});


观察:

如果您处于不同的场景中,您拥有对象可能所在的确切引用路径,则无需添加 orderByChildequalTo.在这种情况下,您可以直接获取对象的路径,因此它不需要来自 firebase 的任何搜索处理.此外,如果您知道该对象必须具有的属性之一,您可以按照下面的代码片段进行操作,使其仅检索该属性而不是整个对象.结果将是一个更快的检查.


Observations:

In case you are in a different scenario which you have the exact ref path where the object might be, you wont need to add orderByChild and equalTo. In this case, you can fetch the path to the object directly so it wont need any search processing from firebase. Also, if you know one of the properties the object must have you can do as the snippet below and make it retrieve just this property and not the entire object. The result will be a much faster check.

//every user must have an email
firebase.database().ref(`users/${userId}/email`).once("value", snapshot => {
   if (snapshot.exists()){
      console.log("exists!");
      const email = snapshot.val();
   }
});