gpt4 book ai didi

typescript - TypeORM:无法读取未定义的属性 'id'

转载 作者:行者123 更新时间:2023-12-02 02:49:42 25 4
gpt4 key购买 nike

我尝试在 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)
...

这里出了什么问题?请帮助我!

最佳答案

来自 typeorm 文档 here :

When using an entity constructor its arguments must be optional. Since ORM creates instances of entity classes when loading from the database, therefore it is not aware of your constructor arguments.

在您的情况下发生的情况是 typeorm 正在创建实体的实例,并且没有在构造函数中传递任何内容。因此 properties 参数是未定义

关于typescript - TypeORM:无法读取未定义的属性 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62227109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com