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

Discord.js搭配Mongoose的inventory指令无响应无报错如何解决?

代码问题排查及修复方案

核心问题点

  • 异步操作逻辑与语法错误
    新用户创建背包数据时,inventory.save()没有加await等待异步操作完成,且then回调的写法错误,catch放在then前会导致异常无法正确阻断后续逻辑,部分场景下会直接打断执行流。
  • 缺少错误捕获机制
    整个执行逻辑没有用try/catch包裹,执行过程中抛出的异常会被静默吞掉,没有报错日志也不会返回响应。其中最容易触发异常的是stats查询逻辑:如果stats集合中不存在Name: 'Boblox'的文档,data1会返回null,执行data1.Ran += 1时会直接抛出类型错误,终止代码执行,导致背包消息无法发送。
  • Discord.js 语法兼容性问题
    如果你使用的是 v13 及以上版本的 Discord.js,发送 embed 不能直接传递 embed 对象,必须将其放在embeds数组中作为参数传递,旧写法会被框架静默忽略,不会发送消息也不会报错。
  • 异步操作未等待
    data1.save()没有加await,存在数据写入丢失的风险。

修复后代码

const { Message } = require('discord.js')
const Client = require('../client')
const Discord = require('discord.js');
const mongoose = require("mongoose")
const Inventory = require('./inventories')
const stats = require('./stats')

module.exports = {
    name: `inv`,
    aliases: ['inventory'],

    /**
     * @param {Client} client
     * @param {Message} message
     * @param {String[]} args
     */
    run: async (client, message, args) => {
        try {
            const noembed = new Discord.MessageEmbed()
                .setColor('RANDOM')
                .setTitle(`${message.author.username}'s Bag`)
                .setDescription(`You have no items :(`)

            const data = await Inventory.findOne({ User: message.author.id })

            if (!data) {
                let inventory = new Inventory({
                    User: message.author.id,
                    Items: []
                })
                await inventory.save()
                await message.reply({ embeds: [noembed] })
            } else {
                const exampleEmbed = new Discord.MessageEmbed()
                    .setColor('RANDOM')
                    .setTitle(`${message.author.username}'s Bag`)
                    .setDescription(!data.Items.length ? "You have no items!" : data.Items.join('\r\n'))
                await message.channel.send({ embeds: [exampleEmbed] })
            }

            const data1 = await stats.findOne({ Name: 'Boblox' })
            if (data1) {
                data1.Ran += 1
                await data1.save()
            } else {
                // 不存在对应统计文档时自动初始化,可根据需求调整
                const newStats = new stats({
                    Name: 'Boblox',
                    Ran: 1
                })
                await newStats.save()
            }
        } catch (err) {
            console.error('inv指令执行错误:', err)
            await message.reply('指令执行出错,请稍后重试').catch(() => {})
        }
    },
    timeout: 2500
}

额外验证点

如果修复后还是没有响应,先确认以下两点:

  1. 你的Discord机器人已经开启了Message Content Intent权限,v13及以上版本需要开启这个权限才能读取普通消息内容触发前缀指令
  2. 确认Inventory集合中存储的Items字段是字符串数组,如果是对象数组,直接join会输出[object Object],需要手动遍历拼接内容

内容的提问来源于stack exchange,提问作者Bob joe12

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 10:27:00