I have this delete controller. Everytime I am deleting a user for example using: http://localhost:3000/api/users/11
even though the user is successfully deleted and it exist, it still showing the message User not found!
on my server response.
Here's my deleted controller code:
exports.deleteUser = async (req, res) => {
const id = req.params.id;
try {
let user = await usersQuery.deleteUser(id);
if (!user) {
return res.json({
success: false,
message: "User not found!",
});
}
return res.json({
success: true,
message: "User was successfully deleted!",
});
} catch (error) {
return;
}
};
If user does not exist, it must show the User not found!
but if the user exist and it was successfully deleted it should show User was successfully deleted!
.
Any idea how to fix this? What am i doing wrong on my code?
CodePudding user response:
You can use console.log(user)
to check what the function actually return and make a condition by the return value.
CodePudding user response:
I guess you are getting error because of return in your success message.
return res.json({
success: true,
message: "User was successfully deleted!",
});
You have return over there. There should be no return actually.
And there is no need to create a variable id
and then using it to delete. You can directly use req.params.id
in delete function.
Since you are deleting the user by searching for its id, you use findByIdAndDelete
.
I have written the code below:
exports.deleteUser = async (req, res) => {
try {
let deletedUser = await usersQuery.findByIdAndDelete(req.params.id);
if (!deletedUser) {
return res.status(404).json({
success: false,
message: "User not found!",
});
}
res.json({
success: true,
message: "User was successfully deleted!",
deletedUser
});
} catch (error) {
return res.send("ERROR FOUND");
}
};
CodePudding user response:
let [err,user] = await usersQuery.deleteUser(id);
if(err){
return res.json({
success: false,
message: "Some error ouccured",
});
}
try to use your deleteUser line like this. if it is error then also check it in logs it might be problem with query.