首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >TypeORM迁移正在运行,无法设定种子(无连接?!在迁移中)

TypeORM迁移正在运行,无法设定种子(无连接?!在迁移中)
EN

Stack Overflow用户
提问于 2021-01-09 04:29:34
回答 1查看 1.4K关注 0票数 1

我正在做我的第一个TypeScript项目,它基于这个模板:https://github.com/ljlm0402/typescript-express-starter

我正在将迁移添加到我们的应用程序中,到目前为止,我们一直依赖于自动迁移功能,并在实体更新时删除/重新创建数据库/表。我们希望通过迁移将“默认用户”添加到我们的系统中...但由于应用程序在迁移中运行up/down功能的方式,出于某种原因,可以创建/删除表,但无法访问这些表中的任何一个以向其中插入数据(??!!)。

我担心这可能是.env / ormconfig.js的问题,而且TS如何编译成JS的层也让我担心出于某种原因,我的应用程序没有读取正确的配置文件。

如何重现这个场景:

ts-node ./node_modules/typeorm/cli.js --config ./ormconfig.js "migration:run"

ormconfig.js:

代码语言:javascript
运行
复制
const env = process.env.NODE_ENV || 'development';

module.exports = {
  type: 'postgres',
  host: process.env.POSTGRESQL_HOST,
  port: process.env.POSTGRESQL_PORT,
  username: process.env.POSTGRESQL_USERNAME,
  password: process.env.POSTGRESQL_PASSWORD,
  database: process.env.POSTGRESQL_DATABASE,
  synchronize: true,
  logging: false,
  entities: [env === 'production' ? 'build/entity/*{.ts,.js}' : 'src/entity/*{.ts,.js}'],
  migrations: [env === 'production' ? 'build/migration/*{.ts,.js}' : 'src/migration/*{.ts,.js}'],
  subscribers: [env === 'production' ? 'build/subscriber/*{.ts,.js}' : 'src/subscriber/*{.ts,.js}'],
  cli: {
    entitiesDir: 'src/entity',
    migrationsDir: 'src/migration',
    subscribersDir: 'src/subscriber',
  },
};

迁移(为简洁起见进行了修剪)

代码语言:javascript
运行
复制
import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';
import userService from '../services/user.service';

export class SeedDefaultUser1610084649009 implements MigrationInterface {
  
  public userService = new userService();

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

    const dbs = await queryRunner.getDatabases(); // returns empty array []
    const schemas = await queryRunner.getSchemas(); // returns empty array []
    console.log(dbs, schemas);

    await queryRunner.createTable(
      new Table({
        name: 'user_entity',
        columns: [
          {
            name: 'id',
            type: 'int',
            isPrimary: true,
          },
          {
            name: 'email',
            type: 'varchar',
          },
        ],
      }),
      true,
    ); // Despite no db connections, this works! tables exist!   

    const user: User = await this.userService.create(
      {
        email: 'admin@email.com',
      },
    ); // This fails with:
       //QueryFailedError: relation "user_entity" does not exist

  }

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

回答 1

Stack Overflow用户

发布于 2021-01-19 01:15:57

要使用TypeOrm插入假数据,需要创建种子而不是迁移。

迁移用于创建表,种子用于填充数据。

您可以按照此medium article创建种子、this npm packagefaker.js

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65635965

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档