javascript - (Mongo/Mongoose) 如何处理等待多个查询结果

标签 javascript mongodb mongoose discord

我正在编写一个 Discord 机器人,该机器人每周生成文本和语音 channel 使用情况的公会统计数据。我的代码将多个 Mongo 查询分为不同的方法:

function getTopActiveTextChannels() {
  let topTextChannels = []
  ChannelModel.find({}).sort({"messageCountThisWeek": -1}).limit(topLimit)
   .exec(channels => {
    channels.forEach(c => {
      topTextChannels.push({"name": c.name, "messageCount": c.messageCount})
    })
    console.log(topTextChannels)
    return topTextChannels
  })
}

function getTopActiveVoiceMembers() {
  let topVoiceMembers = []
  UserModel.find({}).sort({"timeSpentInVoice": -1}).limit(topLimit)
  .exec(users => {
    users.forEach(u => {
      topVoiceMembers.push({"username": u.username, "timeSpentInVoice": u.timeSpentInVoice})
    })
    console.log(topVoiceMembers)
    return topVoiceMembers
  })
}

然后我有一种方法可以调用这两个方法并(目前)将值打印到控制台:

function getWeeklyGuildStats(client) {
  let topActiveTextChannels = getTopActiveTextChannels()
  let topVoiceMembers = getTopActiveVoiceMembers()
  let promisesArray = [topActiveTextChannels, topVoiceMembers]

  Promise.all(promisesArray).then(values => {console.log(values)})
}

执行getWeeklyGuildStats(client)输出:[ undefined, undefined ]。我确信我没有正确使用 promise ,但是当我遵循 Mongoose 的文档时,它告诉我使用 exec() 而不是 then(),但我得到了channels = null 错误。

有人会想到什么吗?这似乎是一个相当常见的模式。有谁有如何用单一方法解决多个 Mongoose 查询的解决方案吗?

最佳答案

Promise.all 应该接受一个 Promise 数组,而您的函数返回普通数组,因此您需要在获取用户和 channel 的帮助器方法中返回整个查询,然后执行您的操作promise.all

之后的逻辑

你的函数可能看起来像这样

function getTopActiveTextChannels() {
  return ChannelModel.find({}).sort({"messageCountThisWeek": -1}).limit(topLimit).exec();
}

function getTopActiveVoiceMembers() {
  return UserModel.find({}).sort({"timeSpentInVoice": -1}).limit(topLimit).exec();
}

那么调用这两个方法的函数将类似于

function getWeeklyGuildStats(client) {
  let topActiveTextChannels = getTopActiveTextChannels()
  let topVoiceMembers = getTopActiveVoiceMembers()
  let promisesArray = [topActiveTextChannels, topVoiceMembers]

  Promise.all(promisesArray).then(values => {
     console.log(values);
     // here you could do your own logic, the for loops you did in the helper methods before
  });
}

关于javascript - (Mongo/Mongoose) 如何处理等待多个查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61165240/

相关文章:

javascript - 谷歌可视化 - 仅在特定点显示图例

javascript - 如何使用美化、语法突出显示的 JSON 结果编写 HTML JSON AJAX 测试工具?

javascript - 参数 "options"不是 Firestore 上的有效 SetOptions 错误

java - 从 Mongo 文档中过滤 YearMonth

javascript - 如何根据条件设置 Mongoose 模式的默认属性值

javascript - 在 Mongodb + Mongoose.js 中动态查询嵌套对象

javascript - 使用 if 语句确定 Firebase 用户是否可以访问某些 React Router 路径

ruby - 通过 Ruby 驱动程序进行 Mongodb 全文搜索和评分

MongoDB Count() 与聚合

MongoDB:使用精益聚合函数