如何映射ObjectID数组查询对应关联对象并修复空返回问题
问题根源
你代码的核心问题是await Promise.all(item)执行后没有接收返回的结果数组,你直接返回的item还是原来的map生成的pending状态Promise数组,JSON序列化Promise自然就变成空对象了。
修正后代码
// 1. 获取所有购买记录的itemId const prevPurchases = await Sales.find({ buyerId }).select(["itemId"]); // 2. 生成查询Promise数组 const itemPromises = prevPurchases.map(async (e) => { try { const item = await Item.findById(e.itemId).select(["image", "name"]); // 可选配置:如果需要返回纯JS对象而非Mongoose文档对象,可以在查询时加lean() // 写法:await Item.findById(e.itemId).select(["image", "name"]).lean() return item; } catch (e) { return null; } }); // 3. 等待所有Promise执行完成,接收最终结果数组 const items = await Promise.all(itemPromises); // 4. 返回结果 return res.status(200).json({ items });
更优方案(推荐)
循环调用数据库查询会产生多次IO请求,性能很差,你可以直接提取所有itemId后用$in语法一次性查完所有关联对象:
// 获取所有购买记录 const prevPurchases = await Sales.find({ buyerId }).select(["itemId"]); // 提取itemId数组 const itemIds = prevPurchases.map(record => record.itemId); // 一次性查询所有关联商品,仅需1次数据库请求 const items = await Item.find({ _id: { $in: itemIds } }).select(["image", "name"]); // 直接返回结果 return res.status(200).json({ items });
内容的提问来源于stack exchange,提问作者camelCaseIsGoodPractice
相关产品推荐
相关产品推荐

