javascript - 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 很陌生,如果这只是一个简单的错误,我很抱歉。提前致谢。
解决方案
您需要处理找不到行的情况:
const row = rows[0];
if (row) {
const { reason } = row;
// rest of your code
} else {
// no rows found
}
推荐阅读
- azure - Azure SQL 数据库的可视化查询设计器?
- python - 是否可以删除输出文件的行?
- html - 我需要以某种方式定位文本的背景
- javascript - 与 GitHub API 用户名搜索相关的函数出现问题
- python - 如何根据分隔符或短语拆分文本列行并在每次拆分时保留名称?
- typescript - ExpressJS:如何将转译的 .js 文件包含在 HTML 中作为静态资源
- reactjs - Redux 正在为映射数组中的所有元素设置重复值
- android - 是否有任何功能可以检测视频是否使用 webview 完成?
- python - 按日期和类别分组的计数器功能
- android - Android Spinner 下拉菜单在向上/向下滚动期间随机丢失项目