我希望我的列表按子名称“ 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', function (request, 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 (request, response) {
var testDBref2 = database.ref('testdb').orderByChild('name')
testDBref2 .once('value', function (snapshot) {
snapshot.forEach(function(child){
console.log(child.val())
});
});
});
它在json中按字母顺序排序(但当然不会显示在网页中)。我是nosql db的新手,所以将不胜感激:)
答案 0 :(得分:0)
如果要按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"
});
});
});