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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37910008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:51:57  来源:igfitidea点击:

Check if value exists in firebase DB

javascriptfirebasefirebase-realtime-database

提问by Gabriel

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.

firebase 中是否有一种方法可以检查数据库中是否存在值?Firebase 有方法.exists(),但根据文档它只检查键。

I have the following structure:

我有以下结构:

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

I want to check if ID with value U1EL5623exists.

我想检查是否U1EL5623存在带值的 ID 。

回答by adolfosrs

The exists()method is part of the snapshotobject 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.

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

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


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 orderByChildand equalTo. In this case you can fetch directly the path to the object so it wont need any search processing from firebase. Also, if you know one of the properties which the object must have you can do as the snippet bellow and make it retrieve just this property and not the entire object. The result will be a much faster check.

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

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

回答by Riccardo Persiani

This is a similar solution if you want to check if an email exists in firebase

如果您想检查 firebase 中是否存在电子邮件,这是一个类似的解决方案

firebase.app().database().ref("shops").orderByChild("email")
   .equalTo(user.email).once("value", snapshot => {

            const userData = snapshot.val();

            // Check if it is a SHOP.
            if (userData) {
              console.log("Shop logged in!");
              this.setState({
                isAdminLoggedIn: false,
                isUserLoggedIn: false,
                isShopLoggedIn: true,
                isNoneLoggedIn: false
              });

            // Check if it is a USER.
            } else {
              console.log("User logged in");
              this.setState({
                isAdminLoggedIn: false,
                isUserLoggedIn: true,
                isShopLoggedIn: false,
                isNoneLoggedIn: false
              });
            }
        });

回答by Mark Thompson

I can't make comments yet, so I'm posting an answer:

我还不能发表评论,所以我发布了一个答案:

To add to the suggested answer, if you wanted to query whether or not any users exist, you can try to improve performance by adding .limitToFirst(1) or .limitToLast(1). This way you can limit your retrieved data to the minimum:

要添加到建议的答案中,如果您想查询是否存在任何用户,您可以尝试通过添加 .limitToFirst(1) 或 .limitToLast(1) 来提高性能。通过这种方式,您可以将检索到的数据限制为最少:

//Check if any users exist
firebase.database().ref(`users`).limitToFirst(1).once("value", snapshot => {
   if (snapshot.exists()){
      console.log("exists!");
      // TODO: Handle that users do exist
      return true;
   }

   // TODO: Handle that users do not exist
});

sources: https://firebase.google.com/docs/reference/js/firebase.database.Query#limitToFirst

来源:https: //firebase.google.com/docs/reference/js/firebase.database.Query#limitToFirst