Mongo/Mongoose二层嵌套Promise统计字段distinct值返回异常如何解决?
问题根因
- 单Promise多次resolve无效:Promise状态只能变更一次,你在遍历distinct值的循环里反复调用resolve,只会返回第一个entry的结果,剩余所有entry的结果都会被丢弃
- 异步操作未正确等待:
distinctValues.map(async entry => {})返回的是Promise数组,你没有等待这部分异步操作全部完成就提前终止了流程,导致返回值不是预期的最终结果 - 重复查询:同一个entry的count查询执行了2次(一次打日志、一次返回值),会产生不必要的数据库开销
- 性能缺陷:先查distinct值再逐个计数属于N+1查询模式,字段枚举值多的时候查询效率极低
修复方案
方案1:基于原有写法修复
// 外层函数需为async,或直接返回Promise.all的结果 const mappedStuff = this.featureFields.map(async field => { // 先拿到当前字段的所有distinct值 const distinctValues = await this.gameModel.distinct(field); // 遍历所有distinct值异步统计数量,等待全部完成 const fieldResult = await Promise.all( distinctValues.map(async entry => { const count = await this.gameModel.count({ [field]: entry }); const resStr = `${field}, ${entry}, ${count}`; console.log(resStr); return resStr; }) ); return fieldResult; }); // 所有字段的结果都返回后,扁平化二维数组得到所有字符串结果 const finalResult = (await Promise.all(mappedStuff)).flat(); // 若需要返回拼接后的整串,可自行调用join方法,比如finalResult.join('\n') return finalResult;
方案2:聚合查询优化(更推荐)
用MongoDB聚合管道一步完成分组统计,仅需1次查询即可拿到单个字段的所有枚举值+计数,性能远高于N+1查询:
const mappedStuff = this.featureFields.map(async field => { const aggregateResult = await this.gameModel.aggregate([ // 按目标字段分组,同时统计计数 { $group: { _id: `$${field}`, count: { $sum: 1 } } } ]); // 转成要求的字符串格式 return aggregateResult.map(item => `${field}, ${item._id}, ${item.count}`); }); const finalResult = (await Promise.all(mappedStuff)).flat(); return finalResult;
内容的提问来源于stack exchange,提问作者Kristoffer Tølbøll
相关产品推荐
相关产品推荐

