NestJs与MySql的连接:错误无法连接到数据库

时间:2020-04-08 16:13:10

标签: mysql typescript nestjs typeorm

你好,我在将nestjs连接到mysql时遇到问题。 每次如果我改变连接方式都会出现不同的错误。 这是conf.ts中的一个

如果尝试使用ocrmconfig.json

{
  "type": "mysql",
  "host": "localhost",
  "port": 3306,
  "username": "root",
  "password": "root",
  "database": "famby_app",
  "entities": ["dist/**/*.entity{.ts,.js}"],
  "synchronize": true,
  "logging": true
}



    [Nest] 27419   - 04/08/2020, 6:02:56 PM   [TypeOrmModule] Unable to connect to the database. Retrying (9)... +4032ms
/Applications/MAMP/htdocs/baby-app-nest/src/user/user.entity.ts:2
import { Entity, Unique, BaseEntity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from "typeorm";
       ^

SyntaxError: Unexpected token {
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
[Nest] 27419   - 04/08/2020, 6:02:56 PM   [ExceptionHandler] Unexpected token { +1ms
/Applications/MAMP/htdocs/baby-app-nest/src/user/user.entity.ts:2
import { Entity, Unique, BaseEntity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from "typeorm";
       ^

SyntaxError: Unexpected token {
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)

我的配置文件

    import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import * as dotenv from 'dotenv';
import { UserEntity } from './user/user.entity';
import { join } from 'path';
import { ConnectionOptions } from 'typeorm';

export const typeOrmConfig: TypeOrmModuleOptions = {
  type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: 'root',
  password: 'root',
  database: 'database_test',
  entities: [__dirname + '/../**/*.entity.{js,ts}'],
  synchronize: true,
  logging: true
};

我尝试了所有可能的方法:/

如果遇到和我一样的问题,有人可以帮助我吗? 谢谢!!!

1 个答案:

答案 0 :(得分:0)

您正在尝试在节点中加载ts文件,这是不可能的。用__dirname + '../**/*.entity.{js,ts}行,您将从dist回到根,然后加载.entity.ts.entity.js的任何东西。因此,您的打字稿源文件正在加载,而Node无法正确解析它们。您应该从该glob中删除ts,或者更好地进行过滤以仅查看您的dist目录(或者说老实话,两者都是最好的)