【问题标题】:TypeORM: Cannot read property 'id' of undefinedTypeORM:无法读取未定义的属性“id”
【发布时间】:2020-06-06 14:11:21
【问题描述】:

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

这里有什么问题?请帮帮我!

【问题讨论】:

  • 完整堆栈跟踪?
  • 嗨兄弟@AluanHaddad,我为这个卡住添加了堆栈,请帮我在这里找到问题,非常感谢

标签: typescript migration typeorm


【解决方案1】:

来自 typeorm 文档here

当使用实体构造函数时,它的参数必须是可选的。由于 ORM 在从数据库加载时会创建实体类的实例,因此它不知道您的构造函数参数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-27
    • 2021-05-29
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2019-11-18
    • 2019-07-27
    • 2021-07-09
    相关资源
    最近更新 更多