根据子对象删除父对象的正确方法

huangapple go评论52阅读模式
英文:

correct way of deleting parent object based on child

问题

I'm trying to delete a parent based on a nested object.
For more information, I'm trying to make a bug-tracker, something much simpler to Jira.
I have a projects collection, when a user creates a project he ends up in the database as a user with 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
    }
]

I would like to check if the user is admin and if so delete the project by using req.params.id. So far I have this much:

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 successfully deleted",
      params: projectId,
      data: checkIfAdmin,
    });
  } catch (err) {
    res.status(400).json({
      status: "Failed",
      message: "Failed to delete this project",
      value: projectId,
    });
    console.log(err);
  }
};

req.user comes from my auth middleware.

Also would love to get some pointers on how to correctly handle user roles in regard to projects and then in future tickets to each project and comments to each ticket.

I have tried all the above outlined.

英文:

I'm trying to delete a parent based on a nested object.
For more information, I'm trying to make a bug-tracker, something much simpler to jira.
I have a projects collection, when a user creates a project he ends up in the database as a user with 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
        }
    ]

I would like to check if the user is admin and if so delete the project by using req.params.id so far i have this much

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);
  }
};

req.user comes from my auth middleware.

Also would love to get some pointers on how to correctly handle user roles in regard to projects and then in future tickets to each project and comments to each ticket.

I have tried all the above outlined

答案1

得分: 1

这是我对这个问题的答案,
如果有更清晰/更好的方法,请添加答案

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) => {
          // 检查用户是否是管理员
          if (user.admin == true) {
            await Project.findByIdAndDelete(projectId);
            res.status(200).json({
              status: "Success",
              message: "项目已成功删除",
              params: projectId,
              data: projects,
            });
          } else
            res.status(400).json({
              status: "Failed",
              message: "您不是管理员",
            });
        });
      });
    } else {
      res.status(400).json({ status: "Failed", message: "找不到任何项目" });
    }
  } catch (err) {
    res.status(400).json({
      status: "Failed",
      message: "删除项目失败",
      value: projectId,
    });
    console.log(err);
  }
};

注意:我已经保留了代码中的注释,并将其保留在翻译中。

英文:

Here is my answer to this problem,
If there is a cleaner/ better way, please add the answer

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);
  }
};

huangapple
  • 本文由 发表于 2023年4月4日 17:50:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927940.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定