i have two entities that needs to be related as follow:
one project can have just one type (type of project), but a type can be associated to multiple projects
i have a DTO for the project entity that looks like this:
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsNumber, IsOptional, IsString } from 'class-validator';
export class CreateProjectDto {
@ApiProperty({ description: 'project name', example: 'ToDo' })
@IsNotEmpty()
@IsString()
readonly name: string;
@ApiProperty({ description: 'type of project', example: 'Personal' })
@IsOptional()
readonly type: string;
}
and i have an entity for both:
project entity
import {
Column,
CreateDateColumn,
Entity,
JoinTable,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { ProjectType } from '../project-type/entities/project-type.entity';
@Entity('projects')
export class Project {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => ProjectType, (type) => type.projects)
type: ProjectType;
}
project-type entity
import { Project } from '@/projects/entities/project.entity';
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
@Entity('project_type')
export class ProjectType {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToOne(() => Project, (project) => project.type)
projects: Project[];
}
but my service is getting an error:
Type 'CreateProjectDto' is missing the following properties from type 'DeepPartial<Project>[]': length, pop, push, concat, and 29 more
this error gets fixed if i change the DTO from readonly type: string; to readonly type: ProjectType;
but when i try to create a project it will ask me for the set of properties that matches type (id , name) and in the frontend i just have a dropdown that renders the options coming from the types entity/table:
i.e:
{id:1, name: 'personal'},
{id:2, name: 'business'},
and when the user select the option it will send just the id of the option not the entire object, so it will throw an error when i try to save the project.
Im not sure if im missing something or maybe i need to add a type_id property to the DTO, but im just joining the backend world, so i don't have too much experience, and even im not sure if this is approach is right. i just read the documentation from NestJS and typeORM
This is probably because you are doing something like this in your service
and projectDto doesn't match your project entity definition as a project has a many to one relation with type. You have to keep your dto definition as you have
But then in your service you will first have to search the Type entity that math the type you received in dto an then assign to the new Project instance your are creating something like this
You should learn more about TypeOrm for better clarification. Hope it helps Lazaro