NestJs TypeORM 无法连接到 mysql

MoS*_*lam 4 mysql node.js typescript typeorm nestjs

我正在尝试连接到 MySQL。我已经在我的根目录的 .env 文件中定义了 db 连接变量,并且我正在初始化app.module.ts文件中的连接。我现在面临的唯一问题是使用 CLI 创建或运行迁移时,我按照 typeorm 文档here来配置连接,但是当我运行时 typeorm migrate:create -n myNewTable,它应该在指定的目录中创建迁移文件,而是它在应用程序根目录中创建它,类似地,我通过使用 之后的-d标志typeorm migrate:create来指定目录解决了这个问题,但是当我尝试运行我的迁移文件时,我得到了这个

在任何配置文件中都找不到连接选项。

这是我的 app.module.ts 文件。

TypeOrmModule.forRoot({
      type: 'mysql',
      host: process.env.TYPEORM_HOST,
      port: parseInt(process.env.TYPEORM_PORT, 10),
      username: process.env.TYPEORM_USERNAME,
      password: process.env.TYPEORM_PASSWORD,
      database: process.env.TYPEORM_DATABASE,
      synchronize: false,
      migrations: [process.env.TYPEORM_MIGRATIONS],
      cli: {
        migrationsDir: process.env.TYPEORM_MIGRATIONS_DIR,
      },
      logging: (process.env.TYPEORM_LOGGING === 'true') ? true : false,
      entities: [__dirname + '/../**/*.entity{.ts,.js}'],
    }),
 
Run Code Online (Sandbox Code Playgroud)

这是我的 .env 文件

# use .ts for development, .js for production
TYPEORM_CONNECTION = mysql
TYPEORM_HOST = 127.0.0.1
TYPEORM_PORT = 3306
TYPEORM_USERNAME = <username>
TYPEORM_PASSWORD = <password>
TYPEORM_DATABASE = <dbname>
TYPEORM_SYNCHRONIZE = true
TYPEORM_MIGRATIONSRUN = true
TYPEORM_LOGGING = true
TYPEORM_ENTITIES = src/**/**.entity.ts
#TYPEORM_ENTITIES = src/**/**.entity.js
TYPEORM_SUBSCRIBERS = src/subscriber/*.ts
#TYPEORM_SUBSCRIBERS = src/subscriber/*.js
TYPEORM_MIGRATIONS = src/database/migration/*.ts
TYPEORM_MIGRATIONS_DIR = src/database/migration
TYPEORM_SUBSCRIBERS_DIR = src/subscriber
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助/提示,​​提前致谢。

小智 14

尝试在 ormconfig.json 或 .env 中更改您的实体目录,它对我有用:

"entities": ["dist/**/**.entity{.ts,.js}"]
Run Code Online (Sandbox Code Playgroud)


Mat*_*ias -1

ormconfig.json您可以在项目根文件夹中指定连接。

看起来像这样

{
    "type": "mysql",
    "host": "localhost",
    "port": <port>,
    "username": "",
    "password": "",
    "database": "",
    "entities": ["dist/**/*.entity{.ts,.js}"],
    "synchronize": true,
    "logging": "all",
    "migrations": [
        "migrations/**/*.js"
    ],
    "subscribers": [
        "subscriber/**/*.js"
    ],
    "cli": {
        "migrationsDir": "<migrations directory>",
        "subscribersDir": "<subscriber directory>"
    }
}
Run Code Online (Sandbox Code Playgroud)

请阅读文档章节了解更多内容

顺便说一句,您可能必须删除dist/文件夹才能使更改生效。