I am currently working with Nest and Mongoose for my project. I need assistance on how to update an object using the FindByIdAndUpdate or FindOneAndUpdate methods. The data is being retrieved from a DTO that utilizes class-validator. In the service layer update method, I am using UpdateQuery to extract data from the controller. This data includes references to other Mongo object IDs as strings.
Could someone please provide guidance on the best approach to updating an object in nest/mongoose? Thank you in advance.
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);