小编典典

无法在 .map() 中执行 SQL 查询

all

我有一个在 req.body 中接收数组的端点。我需要获取该数组,并且对于该数组的每个元素,我需要执行 SQL 更新查询。这是代码:

const approveShifts = (req, res) => {
  try {
    const { guard_id } = req.params;
    const { shiftIDs, isBooked } = req.body;
    shiftIDs.map((shift_id) => {
      connection.query(
        `UPDATE shift SET isBooked=${isBooked}, fk_guard=${guard_id} WHERE shiftID=${shift_id}`,
        (err, rows) => {
          if (!err) {
            res.status(200).json({
              success: true,
              message: `Successfully Approved Shift #${shift_id} for Guard #${guard_id}`,
            });
          } else {
            res.status(404).json({
              success: false,
              message: "Shift Not Found!",
            });
          }
        }
      );
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message,
    });
  }
};

这是我的 req.body:

{
    "shiftIDs": [64],
    "isBooked": 1
}

问题是,无论我做什么样的测试,我得到的唯一输出是“Shift Not Found!” 来自查询的 else 语句。没有其他事情发生。我无法让它工作。有人可以指导我吗?


阅读 86

收藏
2022-07-14

共1个答案

小编典典

这里有几件事 - 首先我建议您使用准备好的语句而不是字符串模板进行查询:

// (assuming this is mysql client?)

connection.query('UPDATE shift SET isBooked = ?, fk_guard = ? WHERE shiftID = ?', [isBooked, guard_id, shift_id], (err, rows, fields) => {...})

// if it's the mysql2 client, use connection.execute() instead of connection.query()

这通过按顺序将每个替换?为数组中的值来工作。这将有助于避免 SQL 注入问题。

其次,您可以在 1 个查询中执行此操作,而不是使用INSQL 运算符进行映射,因为您为每个 shiftID 设置了相同的 isBooked 和 fk_guard 值:

// assuming shiftIDs is an array

connection.query('UPDATE shift SET isBooked = ?, fk_guard = ? WHERE shiftID IN (?)', [isBooked, guard_id, shiftIDs], (err, rows, fields) => {...});

正如其他人所说,您应该console.log(err)res.status(404)看看错误是什么。顺便说一句,如果班次不存在,则不会更新任何行,但也不会引发错误,因此您的响应不会是 404。

2022-07-14