【问题标题】:Firebase NodeJs OrderByChildFirebase NodeJs OrderByChild
【发布时间】:2020-12-26 09:48:29
【问题描述】:

我想让我的列表按子名“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 数据库的新手,所以任何帮助都将不胜感激:)

【问题讨论】:

    标签: node.js firebase express firebase-realtime-database nosql


    【解决方案1】:

    如果您希望键按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"
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多