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

TypeScript中MySQL查询结果存变量后status返回undefined问题

问题分析与解决:tournament.status 返回 undefined

你遇到的undefined问题根源很明确:MySQL查询返回的results是数组类型——哪怕只匹配到一条数据,它也是包含单个RowDataPacket对象的数组。你直接把整个数组赋值给了tournament,而数组本身没有status属性,所以访问tournament.status自然返回undefined。

修改后的代码

pool.query('SELECT * FROM tournament WHERE id = ?', [tournamentId], (error, results) => {
  if (error) {
    console.log(error);
    return; // 出错后直接返回,避免后续无效逻辑执行
  }
  // 取数组第一个元素,拿到具体的赛事对象
  const tournament = results[0];
  console.log(tournament);
  console.log(tournament?.status); // 可选链操作符,防止无数据时报错

  if (!tournament) {
    console.log('Tournament not found');
  } else if (tournament.status === 'completed') {
    console.log(tournament);
  } else if (tournament.status === 'full') {
    console.log('Full');
  }
})

关键修改点

  • 将const tournament = results;改为const tournament = results[0];,这样拿到的才是包含status属性的具体赛事数据对象,而非结果数组。
  • 错误处理中添加return,避免报错后继续执行后续逻辑。
  • 使用?.可选链操作符(ES2020及以上版本支持),当未查询到数据时,tournament?.status会返回undefined而不会抛出类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:03:16