首页 > 解决方案 > 如何使用 TypeORM 迁移将计算数据插入数据库?

问题描述

我有一种情况,我需要在 TypeORM 中的现有表中添加一个新列。我将该列设置为“可为空”,因为表中存在需要添加该列的数据的现有项目,然后才能将该列设置为不可为空。

我一直在尝试编写一个迁移文件来将数据插入到表中每一行的新列中,但它似乎没有保存。

这就是我现在正在尝试的:

import { MigrationInterface, QueryRunner } from 'typeorm';
import { Customer } from '../../entities';
import { generateUrlName } from '../../entities/Customer';

export class fixUrlNameCustomers1584393813738 implements MigrationInterface {
  name = 'fixUrlNameCustomers1584393813738';

  public async up(queryRunner: QueryRunner): Promise<void> {
    const customers = await queryRunner.manager.find(Customer);

    const updatedCustomers = customers.map(customer => {
      customer.url_name = generateUrlName(customer.name);
      return customer;
    });

    await queryRunner.manager.save(updatedCustomers);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {}
}

如您所见,我正在尝试使用名为 generateUrlName 的函数为每个客户填写“.url-name”。在我运行此迁移并从 Postgres 执行查询后,我可以看到迁移没有保存数据。

标签: node.jspostgresqlexpressdatabase-migrationtypeorm

解决方案


推荐阅读