I am someone new to NestJS and was wondering what the best practice for converting a DTO to an entity is, when the DTO’s attributes don’t match up 1:1 with the entities attributes.
For example, i have the following entity definitions:
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToMany(() => questionToCategory, questionToCategory => questionToCategory.category)
public questionToCategories: QuestionToCategory[];
}
export class Question {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
text: string
@OneToMany(() => QuestionToCategory, questionToCategory => questionToCategory.question)
public questionToCategories: QuestionToCategory[];
}
export class QuestionToCategory {
@PrimaryGeneratedColumn()
public questionToCategoryId: number
@Column()
public questionId: number
@Column()
public categoryId: number
@Column()
public order: number
@ManyToOne(() => Question, (question) => question.questionToCategories)
public question: Question
@ManyToOne(() => Category, (category) => category.questionToCategories)
public category: Category
}
with these entity definitions, there is a many to many relationship between question and categories
to save the many to many relation from the question entity, you could do something like this:
questionToCategories: { categoryId: "some_id_value" }
this works fine, however my DTO structure doesn’t match this structure perfectly.
if my question dto is something like the following:
export class CreateQuestionDto {
@IsString()
title?: string;
@IsString()
title?: string;
@IsOptional()
@IsArray()
bundles: string[];
}
where bundles is an array of id’s corresponding to a category. I cant directly save this DTO as the entity, as the bundles field doesn’t match up with questionToCategories. In NestJS is there any best practice to convert the dto to the equivalent representation of the entity
Burh Moment is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.