'How do I delete all posts associated with a user in my node application using mongodb
So, I was wondering why deleteMany() isn't working for me here. I have a node application that uses mongodb as db and Mongoose along with expressjs.
I have a function that delete a user and I would like to delete the user's posts, comments, replies, that have that user's id. I used deleteMany() and passed the user's mongodb _id. But this has refused to work. It is not deleting the user's posts, comments and replies. The user gets deleted but the associated contents are not getting deleted and not returning any error. What is the best way to go about this? I have searched on google but couldn't find anything helpful so far. Here is the function code:
const deleteUser = async (req, res) => {
if (req.user.userId === req.params.id || req.user.role === 'admin') { //we checked if the user id matched
try {
const user = await User.findById(req.params.id) //get the user and assign it to user variable
if (!user) {
return res.status(200).json("User not found")
}
await Post.deleteMany({
_id: user._id
}) //deleting user posts once the username matches with the variable user object .username
await Comment.deleteMany({
author: user._id
}) //delete user's comment by checking the comment author's id.
await Reply.deleteMany({
author: user._id
}) //deletes user's replies
await User.findByIdAndDelete(req.params.id) //delete the user
res.status(200).json("User has been deleted")
} catch (err) {
res.status(404).json("User not found")
}
} else {
res.status(401).json("You can only delete your account!")
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
