MongoDB删除操作无效?Discord.js Bot中ChatListing数据排障求助
问题分析与修复方案
核心问题
数据库删除操作不生效的原因有两个:
ChatListing.findByIdAndDelete是异步方法,你没有添加await关键字,导致代码跳过数据库操作直接执行后续逻辑,删除请求根本没完成。- 混合使用Mongoose的回调模式和
async/await,导致异步流程混乱,且部分错误无法被捕获。
另外,findByIdAndDelete的参数写法冗余:data._id本身就是MongoDB的ObjectId类型,不需要再用mongoose.Types.ObjectId()转换,直接传data._id即可。
修复步骤
- 把
ChatListing.findOne的回调写法改为async/await,消除嵌套,让流程更清晰。 - 给
ChatListing.findByIdAndDelete添加await,确保数据库删除操作完成后再执行后续代码。 - 统一用
try/catch捕获所有异步错误,避免遗漏。
修正后的代码片段
case 'remove': modal.setTitle('Remove a Listing'); const listingIDInput = new TextInputBuilder() .setCustomId('listingIDInput') .setLabel(`What's the ID of your listing?`) .setPlaceholder('EX... 14309') .setMinLength(5) .setStyle(TextInputStyle.Short) .setRequired(true); const rmrow = new ActionRowBuilder().addComponents(listingIDInput); modal.addComponents(rmrow); await interaction.showModal(modal); try { // 改用await替代then,避免嵌套 const modalInteraction = await interaction.awaitModalSubmit({ time: 120_000 }); const listingToRemove = modalInteraction.fields.getTextInputValue('listingIDInput'); // 用await替代findOne的回调写法 const data = await ChatListing.findOne({ GuildID: guild.id, ListingID: listingToRemove }); if (!data) { embed.setTitle('Listing not found') .setColor('Orange') .setDescription('No matching listing found with the provided ID.') .setTimestamp(); await modalInteraction.reply({ embeds: [embed], ephemeral: true }); return; } if (data.MemberID !== member.id) { embed.setTitle('You aren\'t the owner of the listing!') .setColor('Red') .setDescription('You aren\'t capable of removing this listing because you aren\'t the user that posted it.') .setTimestamp(); await modalInteraction.reply({ embeds: [embed], ephemeral: true }); return; } // 删除消息,增加频道存在判断避免报错 const channel = await guild.channels.cache.get(data.Channel); if (channel) { const msg = await channel.messages.fetch(data.MessageID); await msg.delete(); } // 执行数据库删除,添加await确保操作完成 await ChatListing.findByIdAndDelete(data._id); // 回复成功提示 embed.setTitle('Listing successfully removed.') .setColor('Green') .setDescription('⚠️ | Your chat listing has been removed successfully. We\'re sorry to see it go! | ⚠️') .setTimestamp(); await modalInteraction.reply({ embeds: [embed], ephemeral: true }); } catch (err) { console.error(err); embed.setTitle('Error occurred') .setColor('Red') .setDescription('An error happened while processing your request. Please try again later.') .setTimestamp(); await interaction.reply({ embeds: [embed], ephemeral: true }); } break;
额外优化点
- 给
channel添加存在判断,避免因频道已被删除导致的报错。 - 补充了找不到对应列表时的提示逻辑,提升用户体验。
- 区分
modalInteraction与原interaction变量,避免变量名冲突导致的逻辑混淆。
内容的提问来源于stack exchange,提问作者ssolveig
相关产品推荐
相关产品推荐

