首页 > 解决方案 > 无法使用 Node.js 解析 Firebase 的快照

问题描述

我有一个查询,它返回快照;

ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {})

当我用 ; 打印快照时

console.log(snapshot.val());

打印如下;

{'-LBHEpgffPTQnxWIT4DI':
    {
        date: '16.05.2018',
        first: 'let me in',
        index: 1,
        second: 'let others in'
    }
},

我需要记录起息日,即此快照的第一个值。

我试过了;

childSnapshot.val()["first"] 
childSnapshot.val()["date"] 

或者

childSnapshot.child.('first') 
childSnapshot.child.('date') 

但没有成功。

请指出我正在做的错误......

我的完整代码如下;

var indexRef = db.ref("/LastIndex/");
var ref = db.ref("/Source/")

indexRef.on("value", function(indexSnapshot) {
    console.log(indexSnapshot.val());

    var currentIndex = indexSnapshot.val()

    ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {
        console.log(snapshot.val());

        if(snapshot !== null) {
            snapshot.forEach(function (childSnapshot) {

            if(childSnapshot !== null) {
                var newRef = db.ref("/ListTest/");
                var key = newRef.push({
                    "firstLanguageWord": childSnapshot.val()["first"] ,
                    "secondLanguageWord": childSnapshot.val()["second"] ,
                    "wordType": childSnapshot.val()["type"],
                    "date": childSnapshot.val()["date"],
                    "translateType": childSnapshot.val()["transType"]
                });

                currentIndex++;
                indexRef.set(currentIndex);
            }
        });
    }
});

BR,

埃尔登

标签: javascriptnode.jsfirebasefirebase-realtime-database

解决方案


根据您在下面的评论和对原始问题的更新进行更新:

如果您的代码看起来“无限迭代”,那是因为您在第一个查询中使用了 on() 方法。事实上,该on()方法“在特定位置侦听数据更改”,如此所述。

如果您只想查询一次引用,请改用该once()方法。文档在这里


以下是Query,因为您在Reference(以及方法)上调用该orderByChild()方法。equalTo()

ref.orderByChild("index").equalTo(currentIndex)

文档中所述:

即使查询只有一个匹配项,快照仍然是一个列表;它只包含一个项目。要访问该项目,您需要遍历结果:

ref.once('value', function(snapshot) {  
  snapshot.forEach(function(childSnapshot) {
    var childKey = childSnapshot.key;
    var childData = childSnapshot.val();
    // ...   
   }); 
});

所以你应该这样做:

ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {
     snapshot.forEach(function(childSnapshot) {
        console.log(childSnapshot.val().first);
        console.log(childSnapshot.val().date);      
       }); 
});

推荐阅读