【问题标题】:How do I use async await with map in the mongoose?如何在猫鼬中使用带有地图的异步等待?
【发布时间】:2021-07-10 19:06:51
【问题描述】:
 const mapLoop = async _ => {
        console.log('Start')
      
        const promises = books.forEach( async (book) => {
            const ownerInfos = await User.find({_id: book.Owner})  
            return ownerInfos;
            
        })
      
        const ownerInformation = await Promise.all([promises])
        console.log(ownerInformation)
      
        console.log('End')
      }
    
 mapLoop();

books 变量由对象组成,每个对象都有 nameBook、 editionBook、_id 和 Owner(这是一个 id)的键值对。我在这里要做的是通过存储在值“所有者”中的 id 找到书的所有者。但是,ownerInformation 变量正在打印 undefined。

【问题讨论】:

  • .forEach 替换为.map

标签: javascript node.js mongodb mongoose mongoose-schema


【解决方案1】:

forEach() 用于对每个数组元素执行操作,并且不会返回新数组。它也不尊重async/await。因此,在您的任何数据库调用实际上是completed 之前,您的下一行就到达了,这并不重要。随着您的 promises 未定义:await Promise.all([undefined]) 返回 [undefined]

尝试将 books 数组直接映射到 promises 数组。现在,promises 是一个 promises 数组,您可以使用 Promise.allawait 来获得结果。


const promises = books.map(book => User.find({_id: book.Owner});  
           
const ownerInformation = await Promise.all(promises)
console.log(ownerInformation)
 

但是,您可以进行一种优化,您只需进行一个包含您所有_ids 的数据库查询。这使用$in() 运算符,用于在给定数组中搜索字段值:

const bookOwnerIds = books.map(book => book.Owner);
const ownerInformation  = await User.find({'_id': { $in : [bookOwnerIds] });  

另外,请检查您的.bookOwner 是否是猫鼬对象ID 所期望的正确格式。如果没有,您可能必须在上述两种情况下都使用 mongoose.Types.ObjectId(book.Owner) 之类的东西。

【讨论】:

  • 当然,如果对您有帮助,请考虑投票/绿色勾选此答案。
【解决方案2】:
  1. forEach 不返回任何内容(它会在原地 改变一个数组),因此promises始终 未定义。使用 map 代替它返回一个新数组。

  2. map 回调不需要异步,await 不需要find 进程。只需返回承诺。

  3. promises 现在将是一个数组,因此您无需将其包装在 Promise.all 中的新数组中。

    const promises = books.map(book => {
      return User.find({ _id: book.Owner });
    });
    
    const ownerInformation = await Promise.all(promises);
    
    console.log(ownerInformation);
    

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 2018-08-30
    • 2016-06-22
    • 2019-02-15
    • 2019-05-10
    • 2020-10-16
    • 2018-04-13
    • 2018-06-11
    • 1970-01-01
    相关资源
    最近更新 更多