【发布时间】:2021-10-31 21:56:37
【问题描述】:
我在构建中学习。我正在用 Nodejs、reactjs 和 mongodb 构建一个博客 CMS。 我有两个角色:用户和管理员。我希望管理员能够删除任何用户。我编写了使用户能够删除他/她自己的帐户的代码。如何让管理员能够通过单击该用户旁边的按钮来删除该用户?
到目前为止,这是我的代码: 用户删除他/她自己的代码。一旦用户删除了他/她的自我,与该用户相关的所有内容也将被删除。这工作正常。
//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!")
}
});
我如何尝试为管理员编写代码以删除用户:
/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")
}
}
});
当我在邮递员上尝试这段代码时,它一直在加载并且没有发送任何东西。
我知道我没有正确编写函数。请为我提供任何帮助以使我能够实现这一目标。谢谢
【问题讨论】:
标签: node.js