【问题标题】:Iterate through mongoose object of array in Jquery遍历Jquery中数组的猫鼬对象
【发布时间】:2018-03-21 05:51:17
【问题描述】:

我正在尝试使用来自 mongoose 的数据来使用 jquery 在哈巴狗页面上填充数据。 这是我的代码:

test.aggregate(
        [
            {
                $group: {
                    _id: '$status',
                    count: {$sum: 1}
                }
            }
        ], function (err, result) {
            if (err) {
                console.log(err);
            } else {
                console.log(result);
                res.render('graphs', {info: result});
            }
        });

当我将“结果”发送到控制台时,这会提取以下数据:

[ 
  { _id: 'Pending', count: 10 },
  { _id: 'In Progress', count: 10 } 
]

在我的哈巴狗模板中,我试图循环遍历结果并为每个对象提取“_id”和“计数”。我可以使用 for in 循环在节点端执行此操作,但不能在 pug 端执行此操作:

doctype html
html
head
title Main Page
script(type='text/javascript').
var results = "#{info}";
    $.each(results, function () {
        console.log(object);
    });

这是我收到的错误,当我将“信息”放到控制台时,它会给出“[对象对象],[对象对象]”。任何帮助都会很棒。

未捕获的类型错误:无法使用 'in' 运算符在 ([object Object],[object Object] 中搜索 'length'

【问题讨论】:

    标签: javascript jquery node.js mongodb pug


    【解决方案1】:

    您应该使用!{JSON.stringify(info)} 调用将info 转换为JavaScript 中使用的变量的jade 语法:

    doctype html
    html
    head
    title Main Page
    script(type='text/javascript').
      var results = !{JSON.stringify(info)}
      $.each(results, function () {
        console.log(object);
      });
    

    此外,您应该使用适当的缩进,每个级别使用 2 或 4 个空格。

    【讨论】:

    • 正是我需要的。我已经绞尽脑汁好几个小时甚至几天都想弄清楚这一点。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 2021-11-17
    相关资源
    最近更新 更多