代码之家  ›  专栏  ›  技术社区  ›  erdemgc

无法用解析Firebase的快照节点.js

  •  0
  • erdemgc  · 技术社区  · 8 年前

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

    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);
                }
            });
        }
    });
    

    比尔,

    1 回复  |  直到 8 年前
        1
  •  1
  •   Renaud Tarnec    8 年前

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

    如果只想查询一次引用,请使用 once() here .


    以下是一个 Query orderByChild() 方法 Reference equalTo() 方法)。

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

    如前所述 here

    即使查询只有一个匹配项,快照也是 需要循环检查结果:

    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);      
           }); 
    });
    
    推荐文章