英文:
How can I write an edit controller
问题
以下是您要求翻译的内容:
我有一个Node.js后端和一个控制器来添加特定功能。有一个添加功能,但没有更新功能。我该如何编写一个更新功能。我对后端不熟悉,但被分配了这个任务。
以下是该功能的添加功能。我该如何编写一个类似于更新的函数:
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));
}
}
}
EDIT:使用的框架是express.js,ODM是mongoose,数据库是mongodb
请注意,我已经忽略了您提到的代码部分,只返回了翻译好的文本。
英文:
I have a nodeJS backend and a controller to add a specific function. There's an add function but there's no update function. how can I write an update function. I'm not good with backend and I have been tasked with this.
Below is the add function for the feature. How do I write a function like that for update:
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));
}
}
EDIT: the framework used is express.js, ODM is mongoose and the database is mongodb
答案1
得分: 0
以下是代码的翻译部分:
async function updateRole(req, res, next) {
/**
* 构造请求体
* @example
* {
* id: 1, // 角色的ID
* name: 'admin' // 新的角色名称
* }
*/
const body = req.body;
try {
const model = await entityRoles.findById(req.body.id);
/**
* 检查数据库中是否存在模型
*/
if (!model) {
return res.status(httpStatus.OK).send({ message: '未找到ID对应的角色' });
}
/**
* 检查数据库中是否存在具有相同名称的新角色
*
* `body.name !== model.name` 这个语句确保检查角色是否正确
* 因为在前面的语句中,总是会有一个具有旧名称的角色从数据库中获取。
*/
if (body.name !== model.name && (await entityRoles.getByName(body.name))) {
return res.status(httpStatus.OK).send({ message: '名称已存在' });
}
/**
* 在这里添加更多的业务逻辑,例如检查其他字段或名称是否正确
*/
/**
* 最后,使用新数据更新模型并保存到数据库。
*/
model.name = body.name;
/**
* 更新角色的其余部分
* @example
* model.lastUpdatedAt = Date.now();
*/
const saveResponse = await model.save();
return res.status(httpStatus.OK).json(new APIResponse(saveResponse, '实体角色更新成功。', httpStatus.OK));
} catch (e) {
/**
* 检查错误的 `code` 来返回给客户端
*/
if (e.code === 11000) {
return res.status(httpStatus.OK).send({ message: '角色名称已存在,请更新为其他名称。' });
} else {
return res
.status(httpStatus.INTERNAL_SERVER_ERROR)
.json(new APIResponse({}, '添加实体角色时出错', httpStatus.INTERNAL_SERVER_ERROR, e));
}
}
}
请注意,我只翻译了代码部分,不包括问题中的其他内容。
英文:
Your question isn't clear such as: framework, orm library, database. But this below code is sample that you can reference:
async function updateRole(req, res, next) {
/**
* Structure body
* @example
* {
* id: 1, // id of role
* name: 'admin' // new name of role
* }
*/
const body = req.body;
try {
const model = await entityRoles.findById(req.body.id);
/**
* Check have model exist on database
*/
if (!model) {
return res.status(httpStatus.OK).send({ message: 'not found role by id' });
}
/**
* Check new name of role is existed in database
*
* `body.name !== model.name` this statement make sure check role is correctly
* because always exist one role with old name that get from database in previous statement.
*/
if (body.name !== model.name && (await entityRoles.getByName(body.name))) {
return res.status(httpStatus.OK).send({ message: 'name is already exist' });
}
/**
* Add more your business logic at here such as check other filed or name is correctly
*/
/**
* Finally, model will be updated with new data and save to database.
*/
model.name = body.name;
/**
* Update rest of role
* @example
* model.lastUpdatedAt = Date.now();
*/
const saveResponse = await model.save();
return res.status(httpStatus.OK).json(new APIResponse(saveResponse, 'Entity role updated successfully.', httpStatus.OK));
} catch (e) {
/**
* Check `code` of error to return client
*/
if (e.code === 11000) {
return res.status(httpStatus.OK).send({ message: 'name of role is existed. please update a other name.' });
} else {
return res
.status(httpStatus.INTERNAL_SERVER_ERROR)
.json(new APIResponse({}, 'Error adding entity role', httpStatus.INTERNAL_SERVER_ERROR, e));
}
}
}
答案2
得分: 0
async updateRole(req, res, next) {
try {
const roleId = req.params.id; // 从请求参数中提取角色ID
const updatedRoleData = req.body; // 从请求体中提取更新后的角色信息
const existingRole = await entityRoles.findById(roleId);
if (!existingRole) {
return res.status(httpStatus.NOT_FOUND).send({ message: "未找到角色。" });
}
// 使用更新后的角色信息更新现有角色
existingRole.name = updatedRoleData.name;
existingRole.description = updatedRoleData.description;
// 根据需要更新其他属性
const updatedRole = await existingRole.save();
return res.status(httpStatus.OK).json(new APIResponse(updatedRole, '角色更新成功。', httpStatus.OK));
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json(new APIResponse({}, '更新角色时发生错误。', httpStatus.INTERNAL_SERVER_ERROR, error));
}
}
英文:
async updateRole(req, res, next) {
try {
const roleId = req.params.id; // Extract the role ID from the request parameters
const updatedRoleData = req.body; // Extract the updated role information from the reque`enter code here`st body
const existingRole = await entityRoles.findById(roleId);
if (!existingRole) {
return res.status(httpStatus.NOT_FOUND).send({ message: "Role not found." });
}
// Update the existing role with the updated role information
existingRole.name = updatedRoleData.name;
existingRole.description = updatedRoleData.description;
// Update other properties as needed
const updatedRole = await existingRole.save();
return res.status(httpStatus.OK).json(new APIResponse(updatedRole, 'Role updated successfully.', httpStatus.OK));
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json(new APIResponse({}, 'Error updating role.', httpStatus.INTERNAL_SERVER_ERROR, error));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论