如何通过forEach循环与Mongoose正确获取用户数据?
解决forEach中async/await导致数组未填充的问题
你遇到的核心问题是:forEach不会等待异步函数执行完成。当你打印total时,forEach里的await this.userModel.findOne(...)还未完成异步查询,因此total仍是空数组。
以下是三种可行的解决方案:
方案1:使用for...of循环(串行执行)
for...of会等待每个异步操作完成后再进入下一次循环,能保证total被正确填充:
let total = []; for (const id of profile) { const user = await this.userModel.findOne({ _id: id }); total.push(user); } console.log('Service', total); // 此时total已包含所有查询结果
方案2:使用Promise.all(并行执行,效率更高)
将所有查询Promise收集后,用Promise.all等待全部完成,这种方式是并行查询,比串行执行速度更快:
const userPromises = profile.map(id => this.userModel.findOne({ _id: id })); const total = await Promise.all(userPromises); console.log('Service', total);
方案3:直接用Mongoose的$in查询(最优解)
没必要循环发起多次查询,Mongoose支持通过$in操作符一次查询多个ID对应的文档,大幅减少数据库请求次数,是效率最高的方案:
const total = await this.userModel.find({ _id: { $in: profile } }); console.log('Service', total);
内容的提问来源于stack exchange,提问作者Fredrick
相关产品推荐
相关产品推荐

