mysql 类型“RowDataPacket[]”上不存在属性“count”|行数据包[][]|OK数据包|确认数据包[]|结果集标题'

ef1yzkbh  于 2023-01-12  发布在  Mysql
关注(0)|答案(1)|浏览(246)

下面的代码:

import { Request, Response, NextFunction } from "express";

import { pool } from "../config/db";

class User {

  static async findAll(req: Request, res: Response, next: NextFunction) {
    await pool.execute("SELECT * FROM users")
      .then((rows) => {
        res.send(rows[0]);
      })
      .catch(err => console.log(err));
    next();

  }

  static async findById(req: Request, res: Response, next: NextFunction) {
    await pool.execute(
      "SELECT * FROM users WHERE id = ?",
      [req.params.id])
      .then(rows => res.status(200).json(rows[0]))
      .catch(err => console.log(err));
    next();

  };

  static async create(req: Request, res: Response, next: NextFunction) {
    await pool.execute(
      "INSERT INTO users (email, password, username , admin) VALUES(?,?,?,?)",
      [req.body.email, req.body.password, req.body.username = req.body.email, req.body.admin])
      .then(() => {
        res.status(200).json(("user created successfully"));
      })
      .catch(err => console.log(err));
    next();

  }

  static async update(req: Request, res: Response, next: NextFunction) {
    await pool.execute(
      "UPDATE users SET email = ?, password = ?, username = ?, admin = ? WHERE id = ?",
      [req.body.email, req.body.password, req.body.username, req.body.admin, req.params.id])
      .then(() => res.status(201).json("updated user successfully!"))
      .catch(err => console.log(err));
    next();

  }

  static async delete(req: Request, res: Response, next: NextFunction) {
    await pool.execute(
      "DELETE FROM users WHERE id = ?",
      [req.params.id])
      .then(() => res.status(201).json(`deleted user ID = ${req.params.id} successfully!`))
      .catch(err => console.log(err));
    next();

  }

  static async count(req: Request, res: Response, next: NextFunction) {
    await pool.execute('SELECT COUNT(*) FROM users;')
      .then(rows => res.status(200).json(parseInt(rows[0].count)))
      .catch(err => console.log(err));
      next();
  }

}

export { User };

在这一行代码中,我得到了以下错误:

.then(rows => res.status(200).json(parseInt(rows[0].count)))

类型“RowDataPacket[]”上不存在属性“count”|行数据包[][]|OK数据包|确认数据包[]|结果集标头“。
类型“RowDataPacket[]”上不存在属性“count”。ts(2339)
我不知道为什么会发生这种情况,我怎么才能摆脱它?

5vf7fwbs

5vf7fwbs1#

您的选择查询-

SELECT COUNT(*) FROM users;

返回一行一列COUNT(*),但您的代码试图访问名为count的属性(列)。如果将COUNT(*)column alias添加为COUNT(*) count,则它将可用-

static async count(req: Request, res: Response) {
  pool.execute('SELECT COUNT(*) count FROM users;')
    .then(rows => res.status(200).json(rows[0][0].count))
    .catch(err => console.log(err));
}

相关问题