我试图删除基于嵌套对象的父对象。为了获得更多信息,我正在尝试制作一个bug跟踪器,对jira来说简单得多。我有一个项目集合,当用户创建一个项目时,他最终在数据库中作为admin = true的用户。
[
{
"_id": "642beae28c88778b7ec345c3",
"name": "test three",
"priority": 0,
"users": [
{
"admin": true,
"role": 3,
"_id": "642aa3df4add92f56fe8caab"
}
],
"createdAt": "2023-04-04T09:16:18.875Z",
"updatedAt": "2023-04-04T09:16:18.875Z",
"__v": 0
},
{
"_id": "642bec891443d0d5528e4469",
"name": "test one",
"priority": 0,
"users": [
{
"admin": true,
"role": 3,
"_id": "642aa3df4add92f56fe8caab"
}
],
"createdAt": "2023-04-04T09:23:21.480Z",
"updatedAt": "2023-04-04T09:23:21.480Z",
"__v": 0
}
]
我想检查用户是否为admin,如果是,通过使用req.params.id删除项目到目前为止,我有这么多
export const deleteProject = async (req: any, res: Response) => {
const { _id: userId } = req.user;
const projectId = req.params.id;
console.log(projectId);
try {
const checkIfAdmin = await Project.find({ "users._id": userId });
console.log(checkIfAdmin[1], "type of this");
// const projects = await Project.findByIdAndDelete({
// projectId,
// });
res.status(200).json({
status: "Success",
message: "Project has been succesfuly deleted",
params: projectId,
data: checkIfAdmin,
});
} catch (err) {
res.status(400).json({
status: "Failed",
message: "Failed to delete this projects",
value: projectId,
});
console.log(err);
}
};
点播。用户来自我的认证中间件。
还希望得到一些关于如何正确处理项目中的用户角色的指针,然后在未来的每个项目和每个票证的注释中。
我已经尝试了上面列出的所有
以下是我对这个问题的回答:如果有更干净/更好的方法,请加上答案
export const deleteProject = async (req: any, res: Response) => {
const { _id: userId } = req.user;
const projectId = req.params.id;
try {
const projects = await Project.find({ "users._id": userId });
if (projects.length !== 0) {
projects.map((el) => {
el.users.map(async (user) => {
//check if user is admin
if (user.admin == true) {
await Project.findByIdAndDelete(projectId);
res.status(200).json({
status: "Success",
message: "Project has been succesfuly deleted",
params: projectId,
data: projects,
});
} else
res.status(400).json({
status: "Failed",
message: "You are not the admin",
});
});
});
} else {
res.status(400).json({ status: "Failed", message: "No projects found" });
}
} catch (err) {
res.status(400).json({
status: "Failed",
message: "Failed to delete this projects",
value: projectId,
});
console.log(err);
}
};