如何在使用async-await时发布到mongodb中引用的模式。我能够创建get函数,但我很难创建post和put。下面是我的get函数:
发布于 2019-04-03 06:27:08
我认为,在你的请求体中,你应该只传递问题id和用户id。因此,当您使用get task details API获取任务时,mongoose将预先填充数据。
您的请求主体应如下所示
{
issue: "5ca2b1f80c2e9a13fcd5b913",
user: "5ca2b1f80c2e9a13fcd5b90b",
record: {
votary: 80,
development: 90,
test: 100
},
date: "2019-03-01T15:00:00.000Z"
};
,然后将任务详细信息另存为
try {
const task = new TaskModel(req.body);
const result= await task.save()
return api.responseJSON(res, 200, result);
} catch (e)
{
// Error
}
发布于 2019-04-03 02:25:51
只需将post中的代码包装在try/catch中
export const post: Operation = async (req: express.Request, res: express.Response) => {
try {
const param: any = {};
const task = new TaskModel(req.body);
const newTask = await task.save()
return api.responseJSON(res, 200, newTask);
} catch(err) {
// treat error
}
}
发布于 2019-04-03 08:33:41
您不应该保存完整的req.body
,而应该只保存您的模式接受的那些字段。根据Task
模式,issue
和user
字段应该存储id
,而不是req.body
中的完整对象。请尝试此操作并相应地更新您的post方法:
export const post: Operation = async (req: express.Request, res: express.Response) => {
try {
let param: any = {};
const user = {
id: req.body.user.id
};
const issue = {
id: req.body.issue.id
};
param = req.body;
param.user = user.id
param.issue = issue.id
const task = new TaskModel(param);
const newTask = await task.save()
return api.responseJSON(res, 200, newTask);
} catch (e) {
api.responseJSON(res, 400, e)
}
};
https://stackoverflow.com/questions/55485636
复制相似问题