首页 > 解决方案 > Discord.js 无法使用 mySQL 在数组中找到项目时出错

问题描述

我收到此错误:

    C:\Users\redacted\Downloads\redacted\node_modules\mysql\lib\protocol\Parser.js:437
      throw err; // Rethrow non-MySQL errors
      ^ 
TypeError: Cannot read property 'reason' of undefined
  at Query.con.query (C:\Users\redacted\Downloads\redacted\bot.js:83:30)

这是我的代码:

const args = message.content.split(' ').slice(1);
        let member = args.slice(0, 1).join(' ');
        con.query(`SELECT * FROM bans WHERE id=${member}`, (err, rows) => {
            if (err) throw err;
            // console.log("check here "+member);
            let reason;
            reason = rows[0].reason;
            if(reason="undefined") return message.reply(`I did not find any users with that ID banned. You must check by user ID!`);
            if(reason) return message.reply(`I found the user banned for the reason **${reason}**`);

我很迷失在这里。基本上,我需要它在数据库中查找项目。它使用命令+check(此处为id)将名为“id”的列与给定的列进行比较。然后,如果它找到一个,它会在 id 的同一行中提取“原因”。问题是,当运行 +check 但它没有找到与给定 ID 匹配的 ID 时,它会使 Discord 机器人崩溃并给出该错误。我抛出错误(我认为)。我对 mySQL 很陌生,如果这只是一个简单的错误,我很抱歉。提前致谢。

标签: javascriptmysqltypeerrordiscord.js

解决方案


您需要处理找不到行的情况:

const row = rows[0];

if (row) {
  const { reason } = row;
  // rest of your code
} else {
  // no rows found
}

推荐阅读