检查 firebase 数据库中是否存在值 [英] Check if value exists in firebase DB

查看:25
本文介绍了检查 firebase 数据库中是否存在值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

firebase 中是否有一个方法可以检查数据库中是否存在值?Firebase 有方法 .exists(),但根据docs 它只检查密钥.

Is there a method in firebase, which can check if value exist in DB? Firebase has method .exists(), but according to docs it checks only the keys.

我有以下结构:

{
  "users": {
    "-KKUmYgLYREWCnWeHCvO": {
      "fName": "Peter",
      "ID": "U1EL9SSUQ",
      "username": "peter01"
    },
    "-KKUmYgLYREWCnWeHCvO": {
      "fName": "John",
      "ID": "U1EL5623",
      "username": "john.doe"
    }
  }
}

我想检查值为 U1EL5623 的 ID 是否存在.

I want to check if ID with value U1EL5623exists.

推荐答案

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();
   }
});

这篇关于检查 firebase 数据库中是否存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆