【问题标题】:Check if data exists in firebase using Ionic使用 Ionic 检查 Firebase 中是否存在数据
【发布时间】:2020-12-17 05:12:52
【问题描述】:

我正在尝试检查我的 firebase 实时数据库中是否存在某个值。但是,它一直说它不存在。 这是我的代码

check(){
       var checkRef = firebase.database().ref('users');

       checkRef.once('value', function(snapshot) {
        if(snapshot.val().hasOwnProperty('referralCode')) {
          console.log("Referral Code exist.");
        }
        else {
          console.log("Referral Code does not exist.");
        }
     });
 
 
 }

谢谢

我正在使用 Ionic 5

【问题讨论】:

  • 请编辑问题以显示您的数据库结构。目前尚不清楚您希望通过收到的快照检查什么。您很可能只是在查看快照中的错误数据。

标签: javascript firebase ionic-framework firebase-realtime-database


【解决方案1】:

我认为您正在使用 javascript "hasOwnProperty" 方法,而您需要使用 firebase 提供的方法 "hasChild":

// Assume we have the following data in the Database:
{
  "name": {
    "first": "Ada",
    "last": "Lovelace"
  }
}

// Determine which child keys in DataSnapshot have data.
var ref = firebase.database().ref("users/ada");
ref.once("value")
  .then(function(snapshot) {
    var hasName = snapshot.hasChild("name"); // true
    var hasAge = snapshot.hasChild("age"); // false
  });

所以在你的情况下应该是这样的:

check(){
       var checkRef = firebase.database().ref('users');

       checkRef.once('value', function(snapshot) {
        if(snapshot.hasChild('referralCode')) {
          console.log("Referral Code exist.");
        }
        else {
          console.log("Referral Code does not exist.");
        }
     });
 
 }

【讨论】:

    猜你喜欢
    • 2017-12-04
    • 2017-10-21
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    相关资源
    最近更新 更多