【问题标题】:Variable undefined nodeJS MySQL query变量未定义的nodeJS MySQL查询
【发布时间】:2021-08-04 20:40:55
【问题描述】:

我有一个包含不同帖子类别的表,我想从名称中获取类别 ID。示例名称:随机 => id:1。

我得到了这样的变量:

const { name, title, cat, con, user_file } = req.body;
console.log(cat); //returnes the name as it should

这是我的查询:

var sql = "SELECT id FROM cat WHERE cat_name = ?";
db.query(sql, cat, function(err, result) {
    if(!result){
        return next();
    }
    const cat_id = result[0];
});

如果我尝试控制台记录 cat_id,我会得到未定义。我尝试过以许多不同的方式来做这件事,但每次都一样。如果我只是跑

SELECT id FROM cat WHERE cat_name = random

在您的数据库管理器中,它按应有的方式工作并返回 ID。

编辑:目的是获取 id 以将外键插入另一个表。

【问题讨论】:

  • “如果我尝试控制台记录 cat_id,我会得到未定义。” - 你在哪里尝试这样做?显示的代码没有这样的尝试。

标签: javascript mysql node.js


【解决方案1】:

您的 results 是一个空数组。这是(假设您使用的是 mysql 包)因为您的函数调用不正确。

向查询as explained here 传递参数时,您需要传递一个数组 值,而不仅仅是一个值。例如:

connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
  // error will be an Error if one occurred during the query
  // results will contain the results of the query
  // fields will contain information about the returned results fields (if any)
});

在您的情况下,这意味着您正在寻找名字是cat 的第一个字符的猫(例如cat[0])。

【讨论】:

  • 回答问题。我查看了文档并尝试了这个解决方案,但即使它有 cat[0] ,[cat],如果我在它周围添加“”,它仍然是空的......
  • db.query('SELECT id FROM cat WHERE cat_name = ?', [cat], function (err, results) { if(err) {console.log('error');} else {console.log('no error?');} console.log(results); console.log(results[0]); console.log(results[0].id); }); 根本不返回任何内容
  • 然后手动运行 SQL 查询,看看它是否打算返回一些东西。我不知道 mongoose 是否允许您获取它使用的原始 SQL 查询(用于调试),请查看他们的文档。
【解决方案2】:

它最终成为一个问题,变量只保存在查询级别。它 console.logged db.query 中的正确数字和 db.query 中的错误数字。所以现在的解决方案是我猜是把它放在里面。

我的解决方案现在如下所示:

  exports.post = (req, res, next) => {
  let { cat } = req.body;
  let cat_id = 0;

  db.query(
    "SELECT id FROM cat WHERE cat_name = ?",
    [cat],
    async function (err, results) {
      if (!err) cat_id = results[0].id;
      else console.log(err);

      db.query(
        "INSERT INTO posts SET ?",
        { cat_id: cat_id },
        (error, results) => {
          if (error) console.log(error);
          else res.status(200).redirect("/post");
        }
      );
    }
  );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多