【问题标题】:For loop mongoose returned data with javascriptFor loop mongoose 使用 javascript 返回数据
【发布时间】:2014-01-05 03:46:34
【问题描述】:

Mongoose 根据需要返回以下数据:

[Object]
0: Object
    thread_history: Array[12]
        0: Object
            __v: 0
            _id: "52c5be11be9931f90b000002"
            body: "thread message"
            uid: "maarten"
        __proto__: Object
        1: Object
        2: Object
        3: Object

我使用 socket.io 发出这些数据,然后尝试将数据转换为 html。

通常我会使用以下 for 循环将发出的数据转换为 html

socket.on('thread_history', function (thread_data) {
    if(thread_data.thread_history) {
    threads_log.push(thread_data);
        console.log(threads_log);
        var html = '';
        for (var i = 0; i < threads_log.length; i++) {
            html += '<div class="thread_wrapper">' + (threads_log[i].uid ? threads_log[i].uid : 'Server') + ' - ' + threads_log[i].body + '</div>';
        }
        thread_content.innerHTML = html;
        thread_content.scrollTop = content.scrollHeight;
    }
    else {
        console.log("There is a problem: ", thread_data);
    }
});

当然,这不适用于 mongoose 返回的数据。

我根本无法访问这些对象,有人可以帮助我吗?我做错了什么?

【问题讨论】:

  • 你遇到了什么错误?
  • 我的控制台中没有出现任何错误,但是,创建了 1 个 div,其中包含“服务器 - 未定义”。所以它可能在那里失败

标签: javascript for-loop mongoose


【解决方案1】:

看起来您正在循环错误的对象,您正在推送“thread_data”并假设循环“thread_data.thread_history”。

也许改变你将数据推送到的行:

threads_log.push(thread_data.thread_history)

否则,如果您需要日志中的整个 tread_data,请在循环中执行以下操作:

threads_log[i].thread_history.body

【讨论】:

  • 谢谢,我已经采纳了您的两个建议。我现在在控制台中获取数组并出现以下错误:“无法读取未定义的属性 'uid'”。所以我们正在到达某个地方:)(认真的意思)
  • 请不要同时申请两个,使用一个或另一个
  • 我做到了,但后来我得到了和开始一样的结果
  • 太好了,所以如果您在日志中获取数组,那么您正在循环正确的内容。现在,如果您将threads_log[i] 记录在循环中,您会得到什么?
  • [对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象,对象] - 0:对象 1:对象 2:对象 3:对象4:对象 5:对象 6:对象 7:对象 8:对象 9:对象 10:对象 11:对象 12:对象 13:对象
【解决方案2】:

使用 jQuery,我想出了一个非常好的和干净的解决方案。

  socket.on('thread_history', function (thread_data) {
        if(thread_data.thread_history) {
        threads_log.push(thread_data.thread_history);
            console.log(threads_log);
            var html = '';


            // jquery each the results
            $.each(thread_data.thread_history, function(){ 
                html += '<div class="thread_wrapper">' + this.uid + " - " + this.body + '</div>';
            });


            thread_content.innerHTML = html;
            thread_content.scrollTop = content.scrollHeight;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多