首页 > 解决方案 > 使用节点 js 和 mongodb 遍历对象数组

问题描述

我是使用 mongodb 的新手,节点正在尝试循环访问我的数据库中的对象数组并仅使用 res.json 显示对象,在我的 console.log 中它显示所有对象,但在我的邮递员中使用 res.json它只显示一个对象请帮助

我的代码

const course = res.GetUserDT.coursesHandled;
  for (let index = 0; index < course.length; index++) {
            console.log(course[index]);
        }
const course = res.GetUserDT.coursesHandled;
  for (let index = 0; index < course.length; index++) {
            res.json(course[index]);
        }

我的控制台输出


{ courseCode: '2103' }
{ courseCode: '2012' }
{ courseCode: '2062' }

我的邮递员输出


{ courseCode: '2103' }

标签: node.jsmongodb

解决方案


您好,欢迎来到 Stackoverflow。

这里的问题是res.json()向请求者发送一个即时响应 - 这意味着响应已经在您的 for 循环的第一次迭代中发送。

我也想知道为什么你需要那个循环——因为你没有在里面做任何事情。那么你为什么不像这样立即发送数组:

res.json(res.GetUserDT.coursesHandled);

推荐阅读