遍历猫鼬数据数组

时间:2019-09-24 21:05:28

标签: javascript node.js express

我正在尝试从Mongoose中获取数据数组,遍历该数组,并为数组中的每个项目向Three.js场景添加一个对象。

当我尝试在浏览器中渲染场景时,出现错误消息:

“ client_world.js:37未捕获(承诺)TypeError:数据在getData处不可迭代”

但是,当我在查询数据库的get请求中控制台记录数据时,它将所有数据条目打印为数组,但它们必须是可迭代的。

我认为也许数据没有到达javascript文件。

以下是从数据库获取数据的代码:

const indexVR = (req, res) => {
    Upload.find({})
    // .populate('Upload')
    .exec(function (err, docs) { 
        if (err) res.send(err)
        // docs.toString()
        res.json(docs)
        console.log(docs)
    })
};

此函数在以下获取要求中:

router.get('/indexvr', FileCtrl.indexVR);

这是js文件中的代码段:

getData()

async function getData() {
  const response = await fetch('/api/indexvr');
  const data = await response.json;
  console.log(data)

   for (item of data) {
    try {
     scene.add( cube );
    } catch (e) {
     console.error(e)
}
  }
}   

没有使用getData函数登录到控制台的任何内容,但是浏览器正在读取某种空的json对象。

..有人知道我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

您的问题可能像调用.json方法一样简单,而不是引用它。

请参考本文档:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch .json是从fetch返回的响应对象的一种方法。

尝试使用const data = await response.json();