【问题标题】:Working with Mongoose Arrays synchronously via async-await [duplicate]通过 async-await 同步使用 Mongoose 数组 [重复]
【发布时间】:2017-05-07 09:58:23
【问题描述】:

所以我一直试图弄清楚我在我创建的逻辑循环中究竟缺少什么。以下示例密切重现了我的情况:

async function x() {
    const items = await Items.find().exec();
    console.log(items);
    for(item in items) {
        console.log(item);
    }
}

所以对我来说,那个小代码块的结果是 items 包含一个预期的 mongoose 文档数组,但问题是:item 显然是 0。

当我查看 mongoose 文档时,其上唯一为 0 的值是 __v 值,据我了解,它是文档所在的版本。我只是错过了什么,还是这不可能?

注意这会按预期返回:

async function x() {
    const items = await Items.find().exec();
    console.log(items);
    items.forEach(item => {
        console.log(item);
    });
}

这会记录数组和单个 mongoose 文档,问题是我希望在我想要等待的第二个循环中进行另一个异步调用,所以如果这不可能,我将不得不进一步分解它猜,但如果可能的话,我想知道那个 0 是从哪里来的。

编辑:澄清一下,我已经尝试在两者上运行 toObject 但它似乎没有改变任何东西,实际上在数组上它说 toObject 不是数组的函数。

编辑 2:我不是在问为什么 for...in 不好,我是在问为什么它没有迭代我拥有的“数组”,这是因为 mongoose 返回一个集合和 for.. .in 遍历对象的可枚举属性。

【问题讨论】:

标签: arrays node.js mongodb mongoose async-await


【解决方案1】:

使用

遍历数组
for(item in ['a', 'b']) {
  console.log(item)
}

将为您提供数组索引:0, 1

你正在寻找

for(const item of ['a', 'b']) {
  console.log(item)
}

这将打印值:a,b

查看this

【讨论】:

  • 谢谢,我没有意识到 for...of 和 for...in 之间的区别,我认为它们的行为相同。
猜你喜欢
  • 2020-03-06
  • 1970-01-01
  • 2017-10-21
  • 2018-12-10
  • 1970-01-01
  • 2019-04-15
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多