[英]Node.js 12.x AWS lambda does not return using firebase-admin realtime database
[英]How can I return ordered data from Firebase database with Node.js using the firebase-admin module?
我正在嘗試查詢Firebase數據庫以獲取按時間戳排序的數據。
1:這可行,但是返回的數據不是按時間戳排序的:
router.get('/articles', function(req, res, next) {
admin.database().ref('articles').orderByChild('timestamp').once('value').then(function (snapshot) {
let articles = snapshot.val();
console.log(articles);
res.render('articles', articles);
});
});
2:這將根據我的需要返回按時間戳排序的數據(我可以在console.log中看到它),但是出現此錯誤:
// /node_modules/express/lib/response.js:1003
// if (err) return req.next(err);
// ^
// TypeError: req.next is not a function
router.get('/articles', function(req, res, next) {
admin.database().ref('articles').orderByChild('timestamp').on('child_added', function (snapshot) {
let articles = snapshot.val();
console.log(articles);
res.render('articles', articles);
});
});
我不明白我在做什么。 我看到這兩個火力點數據庫調用是不同的,一個是一次 , 然后 (因此它必須是一個承諾..?),另一個是上 (所以我想這只是一個正常的回調...)。
您對這里為什么會發生有任何想法嗎? 抱歉,如果這很明顯,但是我有點初學者。
當您對Firebase數據庫執行查詢時,可能會有多個結果。 因此,快照包含這些結果的列表。 即使只有一個結果,快照也將包含一個結果的列表。
因此,在您的第一個示例中, snapshot
包含了它們:匹配節點的鍵,它們的值以及它們之間的順序。 當您調用snapshot.val()
此數據將轉換為常規JSON對象,該對象沒有空間容納所有三段信息。 此時,訂購信息被刪除。
解決方案是使用snapshot.forEach()
以正確的順序遍歷匹配的節點。
admin.database().ref('articles').orderByChild('timestamp').once('value').then(function (snapshot) {
var articles = [];
snapshot.forEach(function(articleSnapshot)
articles.push(snapshot.val());
});
console.log(articles);
res.render('articles', articles);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.