如何解决Mongoose带过滤条件统计Schema文档数量失败问题?
解决Discord机器人Mongoose警告统计失败问题
问题核心
你当前的代码存在两个关键问题:
- 第一种写法里,
find()后调用countDocuments()属于冗余操作,且未处理数据库查询错误,一旦查询出错,count会返回异常值,导致嵌入消息的警告编号显示异常。 - 第二种写法中,
exec()返回的是Promise对象,直接赋值给count拿到的不是实际数字,而是Promise实例,所以输出的是Promise相关内容而非统计结果。
正确实现方案
方案1:回调式(带错误处理)
直接使用countDocuments()传入查询条件,无需先调用find(),同时补充错误处理逻辑:
WarningSchema.countDocuments({ user_id: user.id.toString() }, (err, count) => { if (err) { // 处理查询错误,比如打印日志或通知管理员 console.error('查询警告数量失败:', err); return; } // 注意:新增警告时,警告编号应为已有数量+1,避免第一条警告显示为0 const warningNumber = count + 1; client.users.cache.get(user.id).send({ embeds: [ new EmbedBuilder() .setTitle('Notice') .setColor('#2B2D31') .setDescription('You have received an official warning on behalf of the RCA Moderation Team.') .addFields( { name: 'Moderator', value: `<@${interaction.user.id}>`, inline: true }, { name: 'Warning #', value: `${warningNumber}`, inline: true }, { name: 'Content', value: reason, inline: false } ) ] }); // 此处可添加将新警告写入数据库的逻辑 });
方案2:Async/Await式(更推荐)
采用现代异步写法,代码结构更清晰,错误处理更直观:
// 确保当前函数为async函数(比如交互处理函数需加async修饰) async function handleWarning(interaction, user, reason) { try { const count = await WarningSchema.countDocuments({ user_id: user.id.toString() }); const warningNumber = count + 1; // 若用户不在缓存,需用fetch获取(fetch为异步操作,需加await) const targetUser = await client.users.fetch(user.id); await targetUser.send({ embeds: [ new EmbedBuilder() .setTitle('Notice') .setColor('#2B2D31') .setDescription('You have received an official warning on behalf of the RCA Moderation Team.') .addFields( { name: 'Moderator', value: `<@${interaction.user.id}>`, inline: true }, { name: 'Warning #', value: `${warningNumber}`, inline: true }, { name: 'Content', value: reason, inline: false } ) ] }); // 将新警告记录写入数据库 await new WarningSchema({ user_id: user.id.toString(), moderator_id: interaction.user.id.toString(), reason: reason, timestamp: new Date() }).save(); } catch (err) { console.error('处理警告失败:', err); await interaction.reply({ content: '处理警告时发生错误,请稍后再试', ephemeral: true }); } }
额外提示
- 若用户不在机器人缓存中,
client.users.cache.get()会返回null,此时必须使用client.users.fetch()获取用户对象(需加await)。 - 所有数据库操作和Discord API调用都可能触发异常,必须添加错误处理逻辑,避免机器人崩溃。
内容的提问来源于stack exchange,提问作者Aestriex
相关产品推荐
相关产品推荐

