将映射引用保存在MongoDB TypeScript中的Object中



我在项目中使用Nest/Mongoose。我想通过FindByIdAndUpdate或FindOneAndUpdate方法更新对象。我正在从带有类验证器的DTO中获取数据。当涉及到服务层更新方法时,我使用UpdateQuery从控制器获取数据。数据由其他Mongo对象id的引用组成,作为strings/string。

请有人提出更新nest/mongoose中对象的最佳方法。提前感谢

class UpdateProjectDto {
@IsArray()
@IsOptional()
@IsString({ each: true })
testSuits: [string];
}
class Project{
@Prop({ type: [MongooseSchema.Types.ObjectId], ref: 'TestSuit' })
testSuits: TestSuit[];
}
project.service.ts
async update(
id: string,
updateQuery: UpdateQuery<UpdateProjectDto>,
): Promise<Project> {
return this.projectModel
.findByIdAndUpdate(
id,
{
...updateQuery,
},
{
new: true,
},
)
}
**Error**
src/projects/controllers/projects.controller.ts:68:50 - error TS2345: Argument of type 'UpdateProjectDto' is not assignable to parameter of type 'UpdateQuery<ProjectDocument>'.
Type 'UpdateProjectDto' is not assignable to type 'ReadonlyPartial<_UpdateQueryDef<DeepPartial<ProjectDocument>>>'.
Types of property 'testSuits' are incompatible.
Type '[string]' is not assignable to type 'DeepPartial<TestSuit>[]'.
Type 'string' has no properties in common with type 'DeepPartial<TestSuit>'.
68     return await this.projectsService.update(id, updateProjectDto);

您可以直接传入UpdateProjectDto而不传入UpdateQuery

async update(id: string, updateQuery: UpdateProjectDto): Promise<Project> {
return this.projectModel.findByIdAndUpdate(id, updateQuery, {
new: true,
});
}

这将返回更新后的对象。

最新更新