node.js - TypeScript, TypeORM, @OneToMany: el constructor simplemente no funciona
Estoy intentando crear dos entidades con una relación de uno a muchos entre ellas, usando node.js, typescript y typeorm. Las entidades en cuestión son "Movie" y "MovieVote". El código es el siguiente.
Entidad de película:
import {Column, Entity, JoinColumn, OneToMany, PrimaryGeneratedColumn} from 'typeorm';
import { ApiModel, ApiModelProperty } from 'swagger-express-ts';
import { MovieVote } from "~/entities/MovieVote";
import { Genre } from './Genre';
@Entity()
@ApiModel({
description: 'The movie entity.',
name: 'Movie',
})
export class Movie {
@PrimaryGeneratedColumn()
id?: number;
@Column({ length: 50 })
@ApiModelProperty({
description: 'The title of the movie',
})
title: string;
@Column({ length: 250 })
@ApiModelProperty({
description: 'The description of the movie',
})
description: string;
@Column({ length: 50 })
@ApiModelProperty({
description: 'The director of the movie',
})
director: string;
@Column({ enum: Genre, type: 'enum' })
@ApiModelProperty({
description: 'The genre of the movie',
})
genre: Genre;
@OneToMany(() => MovieVote, movieVote => movieVote.movie)
votes: MovieVote[];
constructor(title: string, description: string, director: string, genre: Genre) {
this.title = title;
this.description = description;
this.director = director;
this.genre = genre;
this.votes = [];
}
}
Entidad MovieVote:
import {Column, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn} from 'typeorm';
import { ApiModel, ApiModelProperty } from 'swagger-express-ts';
import { User } from "~/entities/User";
import { Movie } from "~/entities/Movie";
@Entity()
@ApiModel({
description: 'The movie vote entity.',
name: 'MovieVote',
})
export class MovieVote {
@PrimaryGeneratedColumn()
id?: number;
@Column()
@ApiModelProperty({
description: 'The vote value'
})
value: number;
@ManyToOne(() => User)
@ApiModelProperty({
description: 'The user responsible for the vote'
})
user: User;
@ManyToOne(() => Movie, movie => movie.votes)
// @ApiModelProperty({
// description: 'The movie the user has voted on'
// })
@JoinColumn({name : 'movieId'})
movie: Movie;
constructor(user: User, movie: Movie, value: number) {
this.value = value;
this.user = user;
this.movie = movie;
}
}
Lo que pasa es que cuando intento ejecutar el código, me da el siguiente error:
Error al iniciar el servidor, Error: No se permiten inicializaciones de arrays en las relaciones de entidades. Por favor, elimine la inicialización de array (= []) de "Movie#votes". Este es un requisito del ORM para que las relaciones funcionen correctamente. Consulte la documentación para más información.
El problema parece estar dentro del constructor de entidades Película. No puedo inicializar la relación "votes" dentro de la entidad con "= []; ", pero no sé cómo debería hacerse. Además, prácticamente no hay mención de esto en la documentación de Typeorm.
Por qué no hay un ejemplo de un constructor de Entidad con este tipo de relación OneToMany en toda la documentación, me supera, pero en fin. Cualquier ayuda sería bienvenida, ¡gracias de antemano!
P.D.: He comentado la anotación @ApiModelProperty en MovieVote porque, por razones desconocidas, esto también provoca un fallo con un "error de _decorador" y algo relacionado con propiedades indefinidas.
Respuesta #1
El problema es el this.votes=[].
En general, el constructor de las entidades no recibe ningún valor y no debería establecer ningún valor. TypeORM se encargará de crear todo por ti.
Si necesitas poder construir tus propias instancias de la clase usando new, puedes hacer algo como lo que yo hago y cambiar a algo como lo siguiente.
constructor(title?: string, description?: string, director?: string, genre?: Genre) {
if (title) {
this.title = title;
this.description = description;
this.director = director;
this.genre = genre;
this.votes = [];
}
}
