如果Firebase数据不是

时间:2017-03-02 18:45:07

标签: javascript firebase firebase-realtime-database

我正在尝试从我的firebase数据库中检索一些数据,但我得到的值是“未定义的”。

这是我将数据保存到数据库的方式:

var database = firebase.database();

        database.ref().push({
        mainArray: mainArray,
        secondArray: secondArray,
        listname: listName,
        mainLanguage: mainLanguage,
        secondLanguage: secondLanguage,

  }, function(error) {
  if (error){

    stopLoader();

    showSnackbar("An error has occured! Please try again later.");
}

这是我读取数据的方式,但listname的值是“未定义”:

 var database = firebase.database().ref().child('codes');
    var codeInput = document.getElementById('mainSearch');

    database.on('value', function(snapshot) {
            if (!snapshot.hasChild(codeInput.value)) {

                codeInput.value = "";
                showSnackbar("A list with this code does not exist!<br><br>Please try another one.")
            }
            else {

               var data = snapshot.val();
               var listname = data.listname;


               console.log(listname);



            }
        });

这是我从数据库中获得的值:

This is the value I get from the database

这是数据库中数据的结构:

This is how the data is structured in the database:

1 个答案:

答案 0 :(得分:1)

我将代码更改为此,现在它完美无缺。问题是我试图从错误的孩子那里获得价值。感谢您的帮助和耐心!

var database = firebase.database().ref().child('codes');
var codeInput = document.getElementById('mainSearch');


database.child(codeInput).on('value', function(snap) {

          var data = snap.val();

          var listName = data.listname;
          var mainLanguage = data.mainLanguage;
          var secondLanguage = data.secondLanguage;
          var mainArray = data.mainArray;
          var secondArray = data.secondArray;

        });