如何解决Firebase NodeJs OrderByChild
我希望我的列表按子名称“ name”按字母顺序排序。当前,这是我用于呈现页面的服务器文件:
app.get('/testpage',function (request,response) {
var testDBref = database.ref('testdb')
testDBref.once('value',function (snapshot) {
var result = snapshot.val()
if (!result) {
result = {}
};
response.render('TestPage.ejs',{
items: result,pageTitle: "My Lists"
});
});
});
但是,当我执行以下操作时:
app.get('/testpage2',response) {
var testDBref2 = database.ref('testdb').orderByChild('name')
testDBref2 .once('value',function (snapshot) {
snapshot.forEach(function(child){
console.log(child.val()) // NOW THE CHILDREN PRINT IN ORDER
var result = snapshot.child('name').snapshot.key
response.render('testpage2.ejs',{
items: result,pageTitle: "My Lists"
});
});
});
});
错误地指出:将标头发送到客户端后无法设置标头,req.next不是函数。
当我刚刚将它控制台到日志时:
app.get('/testpage2',function (snapshot) {
snapshot.forEach(function(child){
console.log(child.val())
});
});
});
它在json中按字母顺序排序(但当然不会显示在网页中)。我是nosql db的新手,所以将不胜感激:)
解决方法
如果要按name
属性的顺序键入键,则必须使用forEach
运算符。这是因为JSON对象中键的顺序是不确定的,但是大多数JSON处理器会按字母顺序返回它们。
但是正如您还发现的那样,您只能调用response.render
一次,因此,如果要返回多个子节点,则必须在forEach
循环之外渲染它们。
解决方案是将子节点转换为数组,然后(如果需要)将每个子节点的键放入数组的对象中。例如:
app.get('/testpage2',function (request,response) {
var testDBref2 = database.ref('testdb').orderByChild('name')
testDBref2 .once('value',function (snapshot) {
var result = [];
snapshot.forEach(function(child){
result.push({ key: child.key,name: child.child('name').val() });
});
response.render('testpage2.ejs',{
items: result,pageTitle: "My Lists"
});
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。