【问题标题】:Get the results of multiple mongoose queries获取多个猫鼬查询的结果
【发布时间】: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


    【解决方案1】:

    您正在寻找类似Promise.all() 的内容。您将从数组中的所有查询中获得结果 (results)。

    let q1 = Company.aggregate([{ $group: { _id: null, mean: {$avg: '$customers'}}}]),
        q2 = Company.aggregate([{ $group: { _id: null, std: {$stdDevPop: '$customers'}}}]),
        queries = [q1, q2].map(q=>q.exec());
    
    Promise.all(queries)
    .then((results)=>{
       console.log(results)
    })
    

    【讨论】:

    • 太棒了!这正是我一直在寻找的。我想知道,结果数组是否总是按照在查询数组中指定其各自查询的顺序填充,还是会根据解决各种承诺的时间来填充?即,在您提供的示例中,结果数组是否总是返回 q1 后跟 q2 的结果?
    • Promise.all 将为您完成这项工作并根据queries 数组的顺序填充results。如此有效,您不必担心 promise 的解决顺序。
    • 谢谢!如果你不介意,我还有一个问题。我想运行上述聚合函数,然后根据其中一个聚合查询的结果运行另一个查询。基本上我想运行另一个查询来获取所有客户少于平均水平的公司。然后,我不仅希望获得客户数量低于平均水平的公司,而且还希望获得平均价值,但我正在努力将这两者传递给下一个 .then() 方法。关于如何做到这一点的任何想法?
    • 我在原始问题中添加了一些额外的细节,所以你知道我的意思。
    • 是的,这是.then() 的常见问题。见here。 async/await 很好地解决了它。如果您使用的是最新的节点版本,则更喜欢。
    猜你喜欢
    • 2017-05-08
    • 2020-02-03
    • 2014-03-03
    • 2021-05-12
    • 2017-12-03
    • 2017-09-21
    • 1970-01-01
    • 2022-11-13
    • 2012-02-05
    相关资源
    最近更新 更多