简体   繁体   English

Firebase无法使用“快照”访问数据

[英]Firebase unable to access data with “snapshot”

I'm writing a web application that uses Firebase, and reading information from the database structured like the following: 我正在编写一个使用Firebase的Web应用程序,并从数据库中读取信息,结构如下:

"user" : {
"-KcNmMmqbSvmVXx2vn4A" : {
  "email" : "firebase@firebase.com",
  "firstname" : "fire",
  "membership_tier" : 1,
  "session_count" : 0,
  "surname" : "base"
}

I'm attempting to read the number of sessions the user has undertaken - however no results are being returned. 我正在尝试读取用户已经进行的会话数 - 但是没有返回任何结果。

What I've tried so far: 到目前为止我尝试过的:

 firebase.database().ref('/users/' + uid).once('value').then(function(snapshot) {
   var sessionCount = snapshot.val().session_count;
 });

Currently snapshot.val() is returning null . 目前snapshot.val()返回null I'm getting an error stating: 我收到一条错误说明:

Uncaught (in promise) TypeError: Cannot read property 'session_count' of null 未捕获(承诺)TypeError:无法读取null的属性'session_count'

uid has been defined, and therefore no issue should be had with accessing the user's information. 已经定义了uid ,因此访问用户信息时不应该有任何问题。

Any pointers would be massively appreciated! 任何指针都会受到大力赞赏!

The below works for me: 以下对我有用:

  //INITIALIZE FIREBASE WEB APP
  firebase.initializeApp(config); 
  var db = firebase.database();
  var auth = firebase.auth();

  db.ref('/whatever/').once('value').then(function(snap) {
    if(snap.val()){
      console.log(snap.val().whateverProperty);
    } else {
      console.log('/whatever/whateverProperty node does not exist!');
    }
  }, function(error) {
    // The Promise was rejected.
    console.log(error);
  });

Looking at the code shared by you, you have defined user in database but trying to access users which could cause the error that you are getting. 查看您共享的代码,您已在数据库中定义了user ,但尝试访问可能导致您获得的错误的users Make sure you are using correct ref . 确保使用正确的ref

Vivek was right that I hadn't used user , and would have also lead to an error, however the main issue was that the reading code resided within a function that had database passed to it, assigned to firebase.database() . Vivek是对的,我没有使用过user ,也会导致错误,但主要问题是读取代码驻留在一个传递给它的database ,分配给firebase.database() Changing the code to this worked fine: 将代码更改为此工作正常:

database.ref('/user/' + uid).once('value').then(function(snapshot) {
  var sessionCount = snapshot.val().session_count;
});

Cheers for the pointers! 欢呼为指针!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM