You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Express+Mongoose编写角色更新接口控制器?

编写NodeJS Express+Mongoose的角色更新控制器函数

你现有基于Express、Mongoose和MongoDB的NodeJS后端,已经实现了addRole角色添加控制器函数,以下是对应的角色更新函数updateRole的实现方案:

原addRole函数参考

async addRole(req, res, next) {
let body = req.body;
const model = new entityRoles(body);
try {
    const alreadyExist = await entityRoles.getByName(req.body.name);
    if (!alreadyExist) {
        const saveResponse = await model.save()
        return res.status(httpStatus.OK).json(new APIResponse(saveResponse, 'Entity role created successfully.', httpStatus.OK));

    } else if (alreadyExist.roleName === req.body.roleName) {
        res
            .status(httpStatus.OK)
            .send({ message: "name is already exist" });
    } else {
        res
            .status(httpStatus.OK)
            .send({ message: "Error Adding entity role" });
    }

} catch (e) {
    if (e.code === 11000) {
        return res
            .status(httpStatus.OK)
            .send({ message: "entity role is already exist with this name" });
    } else {
        return res.status(httpStatus.INTERNAL_SERVER_ERROR).json(new APIResponse({}, 'Error adding entity role', httpStatus.INTERNAL_SERVER_ERROR, e));
    }
}

实现updateRole函数

async updateRole(req, res, next) {
  try {
    // 从URL参数获取要更新的角色ID
    const roleId = req.params.id;
    const updateData = req.body;

    // 1. 检查要更新的角色是否存在
    const existingRole = await entityRoles.findById(roleId);
    if (!existingRole) {
      return res.status(httpStatus.OK).send({ message: "Entity role not found" });
    }

    // 2. 检查新角色名称是否被其他角色占用(排除当前角色自身)
    if (updateData.name) {
      const duplicateRole = await entityRoles.findOne({
        name: updateData.name,
        _id: { $ne: roleId }
      });
      if (duplicateRole) {
        return res.status(httpStatus.OK).send({ message: "Name is already exist" });
      }
    }

    // 3. 执行更新并返回最新数据
    const updatedRole = await entityRoles.findByIdAndUpdate(
      roleId,
      updateData,
      { new: true, runValidators: true }
    );

    // 4. 返回成功响应
    return res.status(httpStatus.OK).json(
      new APIResponse(updatedRole, 'Entity role updated successfully.', httpStatus.OK)
    );

  } catch (e) {
    // 处理唯一索引冲突
    if (e.code === 11000) {
      return res.status(httpStatus.OK).send({ message: "Entity role is already exist with this name" });
    }
    // 处理服务器内部错误
    return res.status(httpStatus.INTERNAL_SERVER_ERROR).json(
      new APIResponse({}, 'Error updating entity role', httpStatus.INTERNAL_SERVER_ERROR, e)
    );
  }
}

关键逻辑说明

  • 角色ID获取:假设路由配置为PUT /roles/:id,通过req.params.id获取目标角色ID,需确保路由配置匹配
  • 存在性校验:先确认目标角色存在,避免对不存在的资源执行更新
  • 名称唯一性校验:更新名称时排除当前角色ID,防止把自身判定为重复
  • 更新参数说明:findByIdAndUpdate的{new: true, runValidators: true}参数,确保返回更新后的最新数据,同时触发Schema定义的验证规则
  • 响应对齐:完全复用addRole的响应格式,包括APIResponse结构和错误提示文案
  • 异常处理:沿用addRole的错误处理逻辑,统一处理索引冲突和服务器内部错误

路由配置示例

在路由文件中添加对应更新路由:

router.put('/roles/:id', yourController.updateRole);

内容的提问来源于stack exchange,提问作者Bruno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 04:32:30