我正在做我的第一个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:
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',
},
};
迁移(为简洁起见进行了修剪)
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> {}
}
发布于 2021-01-19 01:15:57
https://stackoverflow.com/questions/65635965
复制相似问题