我试图像这样在TypeORM中使用镜像:
TableExample.entity.ts
@Entity({ name: 'table_example' })
export class TableExampleEntity {
constructor(properties : TableExampleInterface) {
this.id = properties.id;
}
@PrimaryColumn({
name: 'id',
type: 'uuid',
generated: 'uuid',
default: 'uuid_generate_v4()',
})
id? : string;
}
TableExample.interface.ts
export interface TableExampleInterface{
id? : string;
}
和迁移文件
import {MigrationInterface, QueryRunner, Table} from 'typeorm';
export class createSongEntities1591077091789 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(new Table({
name: 'table_example',
columns: [
{
name: 'id',
type: 'uuid',
generationStrategy: 'uuid',
default: 'uuid_generate_v4()',
isPrimary: true,
},
],
}));
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('table_example');
}
}
运行镜像时,节点服务器抛出此错误 堆栈跟踪
Error during migration run:
TypeError: Cannot read property 'id' of undefined
at new TableExampleEntity (...\src\entities\TableExample.entity.ts:17:34)
at EntityMetadata.create (...\src\metadata\EntityMetadata.ts:524:19)
at EntityMetadataValidator.validate (...\src\metadata-builder\EntityMetadataValidator.ts:112:47)
at ...\src\metadata-builder\EntityMetadataValidator.ts:45:56
at Array.forEach (<anonymous>)
at EntityMetadataValidator.validateMany (...\src\metadata-builder\EntityMetadataValidator.ts:45:25)
...
这是怎么了?请帮帮我!
答案 0 :(得分:3)
来自typeorm文档here:
使用实体构造函数时,其参数必须是可选的。由于ORM在从数据库加载时会创建实体类的实例,因此它不知道您的构造函数参数。
在您的情况下,发生的事情是typeorm正在创建实体的实例,并且未在构造函数中传递任何内容。因此properties
参数为undefined
。