简体   繁体   English

如何解构 object 并使用键和值更新 MySQL?

[英]How to destructure an object and update MySQL with keys and values?

I am passing data from a react frontend to an express backend:我正在将数据从反应前端传递到快速后端:

axios.post('http://localhost/api', {foo: true, bar: false});

In the backend I am updating a MySQL database like在后端,我正在更新 MySQL 数据库,例如

app.post("/user", (req, res) => {
  const {foo, bar} = req.body;
  const sql = `UPDATE users SET foo = ?, bar = ?`;
  connection.query(sql, [foo, bar], (err) => {
    if (err) {
      res.send({err: err});
    } else {
      res.send({updated: true});
    }
  })
});

What if I don't know the keys of the data I'm passing?如果我不知道要传递的数据的键怎么办? Like foo and bar could be whatever.就像 foo 和 bar 可以是任何东西。

I need to know the keys that I am currently destructuring in const {foo, bar} = req.body .我需要知道我目前在const {foo, bar} = req.body中解构的键。 Additionally I need to have them in the column part of the UPDATE string in foo =?此外,我需要将它们放在foo =?中 UPDATE 字符串的列部分中。 and bar =?bar =? . .

I want to do this, to be able to update different values in a database with the same function.我想这样做,以便能够使用相同的 function 更新数据库中的不同值。

Loop over the keys and values and construct the SQL dynamically.循环遍历键和值并动态构造 SQL。

app.post("/user", (req, res) => {
  let whitelist = ["foo", "bar"];
  let checkWhitelist = Object.keys(req.body).filter((e) => whitelist.includes(e)).length > 0;
  if (checkWhitelist) {
    let assign = Object.keys(req.body).map(k => `\`${k}\` = ?`).join(', ');
    let vals = Object.values(req.body);
    const sql = `UPDATE users SET ${assign}`;
    connection.query(sql, vals, (err) => {
      if (err) {
        res.send({err: err});
      } else {
        res.send({updated: true});
      }
    })
  } else {
    res.send({err: "Error"});
  }
});

Note that this is dangerous, since you're trusting the client to send valid column names.请注意,这是危险的,因为您相信客户端会发送有效的列名。 In real life you should white-list the column names.在现实生活中,您应该将列名列入白名单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM