【发布时间】:2022-11-24 07:02:07
【问题描述】:
我有一个简单的“findOne 练习”服务,如果练习的 ID 在数据库中不存在,它会抛出“NotFoundException”。
这是此服务的代码:
async findOne(id: string | Exercice) {
if (!isValidObjectId(id)) {
throw new BadRequestException('ID is not valid');
}
const exercice = await this.exerciceModel
.findById(id)
.populate('bodyPart targetMuscle')
.select('-__v');
if (!exercice) {
throw new NotFoundException('exercice not found');
}
return exercice;
}
当我创建一个程序时,我需要确保我在正文中发送的练习存在于数据库中。所以在我的“创建程序服务”中,我这样调用我的锻炼服务。
async create(createProgramDto: CreateProgramDto) {
const { user, exercices } = createProgramDto;
// some code
exercices.forEach(async (element) => {
await this.exerciceService.findOne(element.exercice)
});
const createProgram = new this.programModel(createProgramDto);
return createProgram.save();
}
我期望的是,如果身体中的一项锻炼不存在,我的“锻炼服务”会抛出“notfoundexception”。相反,我收到了这个错误:
/home/jeremy/src/apps/API/my-exercices/src/modules/exercice/exercice.service.ts:62
throw new NotFoundException('exercice not found');
^
NotFoundException: exercice not found
at ExerciceService.findOne (/home/jeremy/src/apps/API/my-exercices/src/modules/exercice/exercice.service.ts:62:13)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at /home/jeremy/src/apps/API/my-exercices/src/modules/program/program.service.ts:29:6
以下是我发送数据以创建程序的方式:
{
"title": "Test",
"user": "634c1bd3c3d17e1b50c2b946",
"exercices": [
{
"exercice": "637d116882ce1f7cc732d83c",
"totalSet": "1",
"rest": "1"
},
{
"exercice": "637d116882ce1f7cc2d83c",
"totalSet": "1",
"rest": "1"
}
]
}
我确实尝试过在没有循环的情况下使用该服务(通过在代码库中添加一个 ID)并且它有效。但是如果我在循环中使用它,它就不起作用。
【问题讨论】:
标签: nestjs