【发布时间】:2020-07-24 16:12:12
【问题描述】:
我正在编写一个 Discord 机器人,它会为文本和语音频道的使用情况生成每周公会统计数据。我的代码将几个 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 查询?
【问题讨论】:
标签: javascript mongodb mongoose discord