使用Sequelize Model和NodeJS在删除后更新数据库中的记录



我创建了一个可以删除的控制器,但这是不同的,因为它不仅根据ID删除记录,而且在调用delete的API后更新记录。让我在下面演示我的代码:

// delete user
exports.delete = (req, res) => {
const user_id = req.params.user_id;
// Find record by it is id to DELETE
User.findByPk(user_id).then((num) => {
if (num == 1) {
res.status(200).send({
message: "User was deleted successfully!",
data: null,
});
} else {
res.status(500).send({
message: `Cannot delete User with id=${user_id}. Maybe User was not found!`,
data: null,
});
}
});
//After delete must update the is_active field
User.update(
{
is_active: 0,
},
{
where: { is_active: null },
}
);
};

现在我有一个问题,我不知道如何使我的API工作。所以,我希望有人能帮助我解决这个问题,即如何更新删除后的is_active必须为0。我很感激。

您只需要使用async/await而不是then来等待findByPk的结果,然后再调用update:

exports.delete = async (req, res) => {
const user_id = req.params.user_id;
// Find record by it is id to DELETE
const user = await User.findByPk(user_id)
if (user) {
//After delete must update the is_active field
await User.update(
{
is_active: 0,
},
{
where: { is_active: null },
}
);
res.status(200).send({
message: "User was deleted successfully!",
data: null,
});
} else {
res.status(500).send({
message: `Cannot delete User with id=${user_id}. Maybe User was not found!`,
data: null,
});
}
};

通过这种方式,您可以获得一个直接的代码,就像您通常在同步时编写的代码一样。

最新更新