how to delete images when i delete user in mongodb node js code example
Example: delete single image by using user id in node js mongodb
const deleteSingleImageByUserId = async (req, res) => {
try {
const user = await User.findByIdAndUpdate(
req.params.userId,
{
$pull: {
images: {
_id: req.params.imageId,
},
},
},
{ new: true }
);
if (!user) {
return res.status(400).send("User not found");
}
await Imageup.findByIdAndDelete(req.params.imageId);
res.send("Image is deleted successfully!");
console.log("user user: ", user);
} catch (err) {
res.status(500).send("Something went wrong!");
}
};