Firebase的数据检索查询不起作用

时间:2018-12-16 18:56:31

标签: javascript firebase firebase-realtime-database firebase-authentication

db structure

上面是db结构,下面是从firebase数据库检索数据的代码,我无法从db获取数据。我需要帮助从firebase db检索数据。我已附加数据库映像查看我的数据库。

function check(userId,snapcity){
  var rootRef=firebase.database().ref().child('users');
    rootRef.on('child_added', function(snap){
      if(snap.child("userId").val()==userId){

        snapcity=snap.child("city").val();
      }
  });
  console.log(snapcity);
      console.log(ajaxData.geoplugin_city);
  if(snapcity){
    if(snapcity!=ajaxData.geoplugin_city){
      logout();
      alert("you can't login because previously you were logged from "+snapcity );

    }
  }
}
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {

    // User is signed in.
    userId=user.uid;
    //alert(userId);
    var date = new Date();
    var n = date.toDateString();
    var time = date.toLocaleTimeString();
    datetime=n+" "+time;
    snapcity="";
    check(userId,snapcity);
    var database = firebase.database();
    writeUserData(userId,ajaxData.geoplugin_request,ajaxData.geoplugin_city,datetime);
    document.getElementById("user_div").style.display = "block";
    document.getElementById("login_div").style.display = "none";

    var user = firebase.auth().currentUser;

    if(user != null){

      var email_id = user.email;
      document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
      console.log('data');
      console.log(ajaxData);
      html="<p>ip: "+ajaxData.geoplugin_request+"</p><p>Country Code: +44</p><p>Country: "+ajaxData.geoplugin_countryName+"</p><p>Country Abbrevation: "+ajaxData.geoplugin_countryCode+"</p><p>Region Code: "+ajaxData.geoplugin_regionCode+"</p><p>Region Name: "+ajaxData.geoplugin_regionName+"</p><p>City: "+ajaxData.geoplugin_city+"</p><p>Time Zone: "+ajaxData.geoplugin_timezone+"</p><p>Latitude: "+ajaxData.geoplugin_latitude+"</p><p>Longitude: "+ajaxData.geoplugin_longitude+"</p><p>Last Login: "+datetime+"</p>";
      $('#data').html(html);
    }


     } else {
        // No user is signed in.


document.getElementById("user_div").style.display = "none";
        document.getElementById("login_div").style.display = "block";

      }
    });

  [1]: https://i.stack.imgur.com/JVeRD.jpg

1 个答案:

答案 0 :(得分:0)

此:

rootRef.on('child_added', function(snap){
  if(snap.child("userId").val()==userId){
    snapcity=snap.child("city").val();
  }
});

可以替换为:

rootRef.child(userId).once('value', function(snap){
  snapcity = snap.child("city").val();
});

接下来,您需要将需要snapcity 的所有代码移至回调函数中。所以:

rootRef.child(userId).once('value', function(snap){
  snapcity = snap.child("city").val();
  console.log(snapcity, ajaxData.geoplugin_city);
  if(snapcity){
    if(snapcity!=ajaxData.geoplugin_city){
      logout();
      alert("you can't login because previously you were logged from: "+snapcity );
    }
  }
});