我需要使用Sequelize在NODE中执行多次查询。 我尝试使用for执行,但是没有用。 有人可以帮助我吗?
exports.update = async (req, res) => {
for (let i = 0; i < req.body.length; i++) {
const id = req.body[i].id;
const permissao = req.body[i].permissao;
const sql =
`UPDATE tetsiste_usuarios.usuarioGraficos SET permissao = ${permissao} \n
WHERE id = ${id} AND permissao <> ${permissao};`;
sequelize.query(sql, { type: Sequelize.QueryTypes.UPDATE })
.then(data => res.json(data))
}
}
答案 0 :(得分:0)
You need to await
the call the sequelize.query
but that said... you are doing this all wrong. The idea behind using an ORM like Sequelize is that it abstracts the SQL and provides protection against things like SQL injection attacks and malormed queries, which your code is susceptible to. If I mess with the request and pass in this for permissao
it will drop your database table 1; DROP TABLE usuarioGraficos; SELECT 1 FROM dual
. That is bad. You're also calling res.json()
on every loop, which will also result in an error.
The proper way to do this is to use the Model.create()
function for inserts or Model.update()
for updates.
loop insert with sql injection vulnerability
const Sequelize = require('sequelize');
const models = require('./models'); // your model definitions
// an array to store our results
const updates = [];
// use a forEach to get each entry from the body array
for (let i = 0; i < req.body.length; i++) {
// this ID
const id = req.body[i].id;
// this permission
const permissao = req.body[i].permissao;
// update the permission where the ID matches and the permission does not
const update = await models.UsuarioGraficos.update({ permissao }, {
where: {
id,
permissao: {
[Sequelize.Op.ne]: permissao,
},
},
});
// add the result
updates.push(update);
}
// send all the updates outside the loop
res.json(updates);