Javascript 如何在Nest.JS中设置ORM witth.env文件类型的配置
我想用.env文件设置TypeORM的配置,但在尝试运行迁移脚本时遇到问题 我所做的: 1.在package.json中添加了脚本Javascript 如何在Nest.JS中设置ORM witth.env文件类型的配置,javascript,node.js,nestjs,typeorm,Javascript,Node.js,Nestjs,Typeorm,我想用.env文件设置TypeORM的配置,但在尝试运行迁移脚本时遇到问题 我所做的: 1.在package.json中添加了脚本 "migration:generate": "node_modules/.bin/typeorm migration:generate -n", "migration:run": "node_modules/.bin/typeorm migration:run", "migration:revert": "node_modules/.bin/
"migration:generate": "node_modules/.bin/typeorm migration:generate -n",
"migration:run": "node_modules/.bin/typeorm migration:run",
"migration:revert": "node_modules/.bin/typeorm migration:revert",
2.应用程序模块中导入的类型或模块*
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'mysql',
host: configService.get('HOST'),
port: +configService.get<number>('PORT'),
username: configService.get('DATABASE_USERNAME'),
password: configService.get('DATABASE_PASSWORD'),
database: configService.get('DATABASE'),
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
})
}
)],
现在,我正在尝试像这样运行迁移脚本:
npm run migration:generate -n AddUserTable
Error during migration generation:
Error: No connection options were found in any orm configuration files.
我收到这样的错误:
npm run migration:generate -n AddUserTable
Error during migration generation:
Error: No connection options were found in any orm configuration files.
根据文档,它应该是一些或mconfig.json,但它也应该与.env一起工作。请告诉我,我的情况有什么问题?关于错误消息,您应该在根项目中添加ormconfig.json。.env文件在本例中不相关。检查导入
ConfigModule.forRoot()
。应该先进口
如果在env文件中使用这些变量,则不能将forRootAsync用于TypeOrmModule
TYPEORM_CONNECTION = postgres
TYPEORM_HOST = localhost
TYPEORM_PORT = 5432
TYPEORM_USERNAME = postgres
TYPEORM_PASSWORD = 12345
TYPEORM_DATABASE = postgres
TYPEORM_SYNCHRONIZE = false
TYPEORM_MIGRATIONS_RUN = false
TYPEORM_ENTITIES = src/modules/**/*.entity.ts
TYPEORM_MIGRATIONS = db/migrations/*.ts
TYPEORM_LOGGING = true
您也可以尝试以下脚本:
"migration:run": "ts-node --project ./tsconfig.json -r tsconfig-paths/register node_modules/typeorm/cli.js migration:run",
"migration:revert": "ts-node --project ./tsconfig.json -r tsconfig-paths/register node_modules/typeorm/cli.js migration:revert",
"migration:create": "ts-node --project ./tsconfig.json -r tsconfig-paths/register node_modules/typeorm/cli.js migration:create",
"migration:generate": "ts-node --project ./tsconfig.json -r tsconfig-paths/register node_modules/typeorm/cli.js migration:generate"
我也有同样的问题。我按照本文中的配置说明解决了这个问题,它向您展示了如何生成动态
ormconfig.json
文件:
额外的设置有点烦人,但它可以工作
请注意,如果您使用的是typescript,这篇文章将从2019年开始,每2020年更新一次nestjs,您需要更改src
路径,以允许src
或dist
位于config.service.ts
文件中,例如,更改为类似的内容(取决于您的文件结构):
到
我发现我的原始答案被版主删除是完全荒谬的,因为我第一次没有为链接添加足够的上下文。这对我们这些面临这一问题的人真的很有帮助。为什么要阻止它?
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
migrationsTableName: 'migration',
migrations: [__dirname + '/../migration/*{.ts,.js}'],
cli: {
migrationsDir: 'src/migration',
},