2016-11-02 99 views
2

我想弄清楚這個嵌套的順序,沒有我會做的。Node.js + Firebase orderByChild不工作

下面是數據結構的樣品我想訂購:

{ 
    "-KV_Lrm_93Agm8kAuXql": { 
    "body": { 
     "Acceleration": "0.0", 
     "Altitude": "11", 
     "Battery": "12.7", 
     "Date": "2016/09/10", 
     "order": 1, 
     "time": "2016-10-19T20:26:32Z" 
    } 
    }, 
    "-KV_LuTfJ9VrKRHoRWuw": { 
    "body": { 
     "Acceleration": "0.0", 
     "Altitude": "11", 
     "Battery": "12.7", 
     "Date": "2016/09/10", 
     "order": 5, 
     "time": "2016-10-21T20:26:32Z" 
    } 
    }, 
    "-KV_Lx9VABuEB8D3I-i1": { 
    "body": { 
     "Acceleration": "0.0", 
     "Altitude": "11", 
     "Battery": "12.7", 
     "Date": "2016/09/10", 
     "order": 2, 
     "time": "2016-10-01T20:26:32Z" 
    } 
    }, 
    "-KV_LzQOM3rHEKQuwyHQ": { 
    "body": { 
     "Acceleration": "0.0", 
     "Altitude": "11", 
     "Battery": "12.7", 
     "Date": "2016/09/10", 
     "order": 10, 
     "time": "2016-09-01T20:26:32Z" 
    } 
    }, 
    "-KV_M0fdznAbKanHoY91": { 
    "body": { 
     "Acceleration": "0.0", 
     "Altitude": "11", 
     "Battery": "12.7", 
     "Date": "2016/09/10", 
     "order": 6, 
     "time": "2016-09-20T20:26:32Z" 
    } 
    } 
} 

%的火力文檔(https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html),你可以做一個「深路徑查詢」。就我而言,如果我想通過爲了排序我應該能夠做到:

.orderByChild("body/order") 

但這沒什麼。它對結果的排序沒有影響。我已經嘗試在日期和時間上訂購,並且都沒有工作。這是我的完整節點功能。這返回結果,只是沒有訂購:

app.get('/api/xirgo-data', function(req, res) 
{ 
    var ref = db.ref("xirgo"); 
    ref 
    .orderByChild("body/order") 
    .on("value", function(snap) { 
     return res.json(snap.val()); 
    }); 
}); 

謝謝!

回答

6

當您在Firebase中請求查詢的值時,生成的快照將包含匹配子項的鍵,值和排序信息。

但是,當您將其轉換爲字典/關聯數組/ JavaScript對象時,由於JavaScript對象固有地無序,所以排序信息丟失。

爲了確保您能夠訪問正確的順序相匹配的項目,使用內置DataSnapshot.forEach()方法:

var ref = db.ref("xirgo"); 
ref 
.orderByChild("body/order") 
.on("value", function(snapshot) { 
    snapshot.forEach(function(child) { 
     console.log(child.key+': '+child.val()); 
    }); 
}); 
+0

這是偉大的,謝謝! – Jesse

+0

完美的答案。 – Tarun