猫鼬将不会执行findById回调

我开始失去理智。为什么这个简单的猫鼬命令不起作用?由于模式更改,我正在编写一个脚本来更新数据库中的项目,无论出于何种原因,我都无法使实际的更新方法正常工作。他们不会出错,也不会出错。他们只是不执行。我脚本中的所有其他内容(与db连接交互)都运行良好。

这是我的代码的要旨:

const db = require('../../server/db');


async function itemMigration() {

  const items = await db.Items.find().exec();

  if (items) {
    items.forEach( async item => {
      console.log(item); // this works! It logs the item to my console.

      // this doesn't do anything.
      await db.Items.findById(item._id,(err,doc) => {
        if (err) {
          console.log(err)
        }
        console.log(item.type)
        doc.set(item);
        doc.save();
      })
    }
  }
}

我希望这段代码能做的是在数据库中找到所有items,对其进行迭代,然后更新每个findById()。第一部分按预期工作。我得到了项目,并将每个项目记录到控制台。 await部分是不执行的部分。我已经尝试过使用/不使用$var命令了……没有区别。我应该在控制台上看到日志,但是没有出现?‍♂️?‍♂️

laonongding 回答:猫鼬将不会执行findById回调

在等待异步功能时,不应提供回调函数。

这是您的代码的外观:

try {
    const doc = await db.Items.findById(item._id)
    doc.set(item);
    await doc.save();

} catch (error) {
    console.error(item.type)   
}

PS:如果您希望以正确的顺序排列商品,请从async中删除items.forEach( async item ...
,只需使用常规的forawait它的身体。

本文链接:https://www.f2er.com/3155991.html

大家都在问