【发布时间】:2019-01-26 02:35:22
【问题描述】:
我正在使用 Mongoose 运行多个聚合查询,并且出于我的应用程序逻辑的目的,我需要在同一个地方访问这些聚合查询的结果。
我需要计算的一件事是集合中字段的平均值,另一件事是标准差。
Company.aggregate([{ $group: { _id: null, mean: {$avg: '$customers'}}}])
Company.aggregate([{ $group: { _id: null, std: {$stdDevPop: '$customers'}}}])
我知道我可以分别在这两个上运行 exec 并使用 then() 方法单独获取结果,但是我将如何一起访问这些结果然后一起使用这两个结果。我想我的问题更多是关于承诺的。有没有办法将上面的两个查询放入一个数组中,然后在数组中的这两个 promise 都解决后执行一个函数?
有没有一种方法可以组合 Promise,以便我可以在组合后的 Promise 中运行 then()?
编辑:
let q1 = Company.aggregate([{ $group: { _id: null, mean: {$avg: '$customers'}}}]),
let q2 = Company.aggregate([{ $group: { _id: null, std: {$stdDevPop: '$customers'}}}]),
queries = [q1, q2].map(q=>q.exec());
Promise.all(queries)
.then((results)=>{
const averageCustomers = results[0][0].mean;
const companies = Company.find({ customers: { $lt: averageCusomters } });
return companies.exec();
})
.then((results)=>{
//here I only have access to the companies that have less than average customers.
//I no longer have access to the average customers across
//all companies or their standard deviation.
})
【问题讨论】:
标签: mongoose es6-promise