Hi i want to throw an error when try to delete a row in my sql database, and the id is not in the table.
Here is my model that receive from controller the id. (this id is not in the table of training)
Training.deleteNewVariations = function (id, result) {
console.log('id deleteNewVariations', id)
dbConn.query(`DELETE FROM training WHERE id='#${id}'` , function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
result(null, res);
}
});
};
And the result of the function in controller:
function deleteNewVariations(req, res) {
const { id } = req.query;
Training.deleteNewVariations(id, function (err, examples) {
console.log('deleteNewVariations', examples)
if (err) {
res.status(500).send({ message: "Server Error." });
} else {
if (!examples) {
res.status(404).send({ message: "Not examples to Delete by this Id" });
} else {
console.log('examples deleteNewVariations ', examples)
res.status(200).send({ message: "Variaciones Borradas Correctamente"});
}
}
})
}
Always send me res.status(200).send({ message: "Variaciones Borradas Correctamente"});
Where is my mistake?
here my DDL:
CREATE TABLE `training` (
`id` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`idResponse` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`description` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`examples_new` json DEFAULT NULL,
`examples_edit` json DEFAULT NULL,
`examples_production` json DEFAULT NULL,
`timestamp_create` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`timestamp_update` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
CodePudding user response:
It's not a SQL error to try to delete rows that don't exist.
You can use res.affectedRows
to tell if any rows were found and deleted.
Training.deleteNewVariations = function(id, result) {
console.log('id deleteNewVariations', id)
dbConn.query(`DELETE FROM training WHERE id='#${id}'`, function(err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else if (res.affectedRows == 0) {
console.log(`error: #${id} not found`);
result(new Error(`#${id} not found`), null);
} else {
result(null, res);
}
});
};