I am learning by building. I am building a blog CMS with Nodejs, reactjs, and mongodb. I have two roles: users and admin. I would like admin to be able to delete any user. I wrote codes that enabled a user to delete his/her own account. How do I go about making the admin to be able to delete any user by clicking a button next to that user?
Here are my codes so far: code for a user to delete him/her self. Once a user deletes him/her self, everything associated with the user also gets deleted. This is working fine.
//delete logic
router.delete("/:id", async (req, res) =>{
if(req.body.userId === req.params.id){//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
try{
await Post.deleteMany({username: 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(500).json(err) //this handles the error if there is one from the server
}
}catch(err){
res.status(404).json("User not found")
}
} else{
res.status(401).json("You can only update your account!")
}
});
How I tried to write the code for admin to be able to delete a user:
/delete a user by an admin
router.delete("/:id", async (req, res) =>{
if(req.body.userId === req.params.id){
const user = await User.findOne({username: req.body.username})
if(user && user.role === "admin"){
try{
const regUser = await User.findById(req.params.id)//get the user and assign it to user variable
try{
await Post.deleteMany({username: regUser._id})//deleting user posts once the username matches with the variable user object .username
await Comment.deleteMany({author: regUser._id})//delete user's comment by checking the comment author's id.
await Reply.deleteMany({author: regUser._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(500).json(err) //this handles the error if there is one from the server
}
}catch(err){
res.status(404).json("User not found")
}
}else{
res.status(401).json("You do not have the permission")
}
}
});
When I tried this code on postman, it kept on loading and didn't deliver anything.
I know that I am not writing the function properly. Kindly provide me with any help to enable me achieve this. Thank you