我正在尝试查询 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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句