You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB删除操作无效?Discord.js Bot中ChatListing数据排障求助

问题分析与修复方案

核心问题

数据库删除操作不生效的原因有两个:

  1. ChatListing.findByIdAndDelete是异步方法,你没有添加await关键字,导致代码跳过数据库操作直接执行后续逻辑,删除请求根本没完成。
  2. 混合使用Mongoose的回调模式和async/await,导致异步流程混乱,且部分错误无法被捕获。

另外,findByIdAndDelete的参数写法冗余:data._id本身就是MongoDB的ObjectId类型,不需要再用mongoose.Types.ObjectId()转换,直接传data._id即可。

修复步骤

  1. 把ChatListing.findOne的回调写法改为async/await,消除嵌套,让流程更清晰。
  2. 给ChatListing.findByIdAndDelete添加await,确保数据库删除操作完成后再执行后续代码。
  3. 统一用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:25:24