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

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

问题描述

在firebase中是否有方法可以检查数据库中是否存在值? Firebase的方法 .exists(),但根据docs只检查密钥。我有以下结构:

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

$ / code>

我想检查ID是否小于code> U1EL5623 存在。

解决方案

>方法,但您可以使用以下逻辑来处理它。

  ref.child(users)。orderByChild( (value,snapshot => {
const userData = snapshot.val();
if(userData){
console)。 log(exists!);
}
});






观察:



如果你在不同的场景中,你有精确的ref对象可能是你不需要添加 orderByChild equalTo 。在这种情况下,您可以直接获取对象的路径,以便不需要从Firebase进行任何搜索处理。同样在这种情况下,如果您知道对象必须拥有的某个属性,则可以像下面的代码段那样执行操作,并使其仅检索此属性而不是整个对象。结果将是一个更快的检查。

  //每个用户必须有一个电子邮件
firebase .database().ref(`users / $ {userId} / email`).once(value,snapshot => {
const email = snapshot.val();
if ){
console.log(user exists!);
}
});


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 keys. 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.

解决方案

There is no explicit exists() method but you can work with the following logic to handle it.

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


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 directly the path to the object so it wont need any search processing from firebase. Also in this case, 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.

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

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

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