NestJS Typeorm save one to many relationship

Viewed 367

I am trying to save an array of objects within my nestjs project in a one to many relationship.

The frontend gives me something like this to work with:

[
{
"actor":"actorname",
"role":"actorrole"
},
{
"actor":"actorname2",
"role":"actorrole2"
}
]

in order to save all those I created a movie entity and an actor entity like this:

actor.entity.ts

//imports
@Entity()
export class Actor {
    @PrimaryGeneratedColumn()
    id: number;

    @ManyToOne(() => Movie, (movie) => movie.actors)
    movieId: number;

    @Column()
    role: string;

    @Column()
    actor: string;
}

movie.entity.ts

//imports
@Entity()
export class Movie {
    @PrimaryGeneratedColumn()
    id: number;

    //more stuff

    @OneToMany(() => Actor, (actor) => actor.movieId)
    actors: Actor[];
}

the issue now is, my frontend is returning the JSON data as a whole string, so I have to JSON.parse() it first and accept it within my dto like this:

//imports
export class CreateMovieDto {
    actorsArray: string;
}

now my problem is saving the json data

//imports
@EntityRepository(Movie)
export class MoviesRepository extends Repository<Movie> {
    async createMovie(
        createMovieDto: CreateMovieDto,
        fileName: string,
        filePath: string,
    ) {
        const movie = this.create(createMovieDto);

        let actorsArray = JSON.parse(createMovieDto.actorsArray);
        //how do i save it now together with the movie?
        
        try {
            //await this.save(movie); disabled for now
            return movie;
        } catch (error) {
            if ((error.code = 'ER_DUP_ENTRY')) {
                console.log(error);
                throw new ConflictException('Movie already exists');
            } else {
                console.log(error);
                throw new InternalServerErrorException();
            }
        }
    }
0 Answers
Related