我正在编写一个 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/