【问题标题】:Connection "default" was not found with TypeORM未使用 TypeORM 找到连接“默认”
【发布时间】:2018-09-22 11:08:42
【问题描述】:

我将 TypeORM 与 NestJS 一起使用,但无法正确保存实体。

连接创建成功,postgres 在 5432 端口上运行。凭证也可以。

但是,当我需要使用 entity.save() 保存资源时,我得到了:

Connection "default" was not found.


Error
    at new ConnectionNotFoundError (/.../ConnectionNotFoundError.ts:11:22)

我检查了 TypeORM ConnectionManager (https://github.com/typeorm/typeorm/blob/master/src/connection/ConnectionManager.ts) 的源文件,但似乎 TypeORM 第一次创建连接时,如果我们不提供连接,它的属性是“默认”名称,对我来说就是这种情况。

我将 TypeORM 设置为 TypeOrmModule

TypeOrmModule.forRoot({
      type: config.db.type,
      host: config.db.host,
      port: config.db.port,
      username: config.db.user,
      password: config.db.password,
      database: config.db.database,
      entities: [
        __dirname + '/../../dtos/entities/*.entity.js',
      ]
    })

当然我的常数是正确的。有什么想法吗?

【问题讨论】:

  • 我假设您必须将 entities 提供给 TypeORM 配置(例如 entities: 'src/*/**.entity.ts')。
  • 是的,我以这种方式引用了我的实体:entities: [ __dirname + '/../../dtos/entities/*.entity.js', ],我编辑了我的帖子

标签: node.js postgresql typeorm nestjs


【解决方案1】:

在我的情况下,我有一个包含多个连接的数组,而不仅仅是一个。您有 2 个选择。

  • 至少有一个default 命名连接,例如:
createConnections([
  {
    name: 'default',
    type: 'mysql',
    host: 'localhost',
    port: 3306,
    username: 'root',
    password: 'root',
    database: 'users',
    entities: [`${__dirname}/entity/*{.js,.ts}`],
    synchronize: true,
    logging: true
  }
]);
  • 具体使用连接时:
import {getConnection} from "typeorm";

const db1Connection = getConnection("db1Connection");
// you can work with "db1" database now...

【讨论】:

    【解决方案2】:

    在验证两个包中的 TypeOrm 版本相同后,即@InsOp 提到的外部包和消费者存储库仍然存在问题,然后问题可能是-

    基本上当我们创建外部包时——TypeORM 会尝试获取 "default" 连接选项,但如果未找到则抛​​出错误:

    ConnectionNotFoundError:找不到连接“默认”。

    我们可以通过在建立连接之前进行某种健全性检查来解决这个问题 - 幸运的是,我们在 getConnectionManager() 上有 .has() 方法。

    import { Connection, getConnectionManager, getConnectionOptions, 
      createConnection, getConnection, QueryRunner } from 'typeorm';
        
        async init() {
        let connection: Connection;
        let queryRunner: QueryRunner;
    
         if (!getConnectionManager().has('default')) {
            const connectionOptions = await getConnectionOptions();
            connection = await createConnection(connectionOptions);
          } else {
            connection = getConnection();
          }
    
        queryRunner = connection.createQueryRunner(); 
     }
    

    上面是一个快速代码-sn-p,它是此问题的实际 根本原因,但如果您有兴趣查看完整的工作存储库(不同示例)-

    • 外部 NPM 包:
    • 上述包的消费者:nest-typeorm-postgre(具体文件-package.json, src/countries/countries.service.ts & countries.module.ts

    【讨论】:

      【解决方案3】:

      我们正在使用 lerna 并使用包 B 中库 A 中的代码。

      问题是每个包中的两个 TypeOrm 版本不同。

      解决方案是确保您在每个包中安装完全相同的版本。

      为了安全起见,请删除您的 node_modules 目录并使用 yarn installnpm install 重新安装所有内容

      检查您的yarn.lock 是否有多个typeorm 条目,并确保只有一个。

      【讨论】:

      • 如果您在使用npm link 时遇到此错误,请改用npm install $(npm pack <path_to_linked_lib> | tail -1)。这确保了目标项目中只安装了一个匹配的 typeorm 版本(如果 typeorm semver 版本匹配)。
      【解决方案4】:

      我知道这很奇怪,但有人可能需要这个:

      Windows相关原因。

      由于当前位置设置为小写驱动器号 (d:/apps/app-name/etc),我遇到了同样的错误。
      一旦我将目录更改指令更新为使用大写 D (D:/apps/app-name/etc),问题就得到了解决。

      【讨论】:

        【解决方案5】:

        我按照以下方法创建Database 类。如果连接不存在,则创建连接,否则返回现有连接。

        import { Connection, ConnectionManager, ConnectionOptions, createConnection, getConnectionManager } from 'typeorm';
        
        export class Database {
          private connectionManager: ConnectionManager;
        
          constructor() {
            this.connectionManager = getConnectionManager();
          }
        
          public async getConnection(name: string): Promise<Connection> {
            const CONNECTION_NAME: string = name;
            let connection: Connection;
            const hasConnection = this.connectionManager.has(CONNECTION_NAME);
            if (hasConnection) {
              connection = this.connectionManager.get(CONNECTION_NAME);
              if (!connection.isConnected) {
                connection = await connection.connect();
              }
            } else {
        
              const connectionOptions: ConnectionOptions = {
                name: 'default',
                type: 'mysql',
                host: 'localhost',
                port: 3306,
                username: 'root',
                password: 'password',
                database: 'DemoDb',
                synchronize: false,
                logging: true,
                entities: ['src/entities/**/*.js'],
                migrations: ['src/migration/**/*.js'],
                subscribers: ['src/subscriber/**/*.js'],
              };
              connection = await createConnection(connectionOptions);
            }
            return connection;
          }
        }
        
        
        

        如果您使用的是 webpack,请确保实体是专门导入并以数组形式返回的。

            import {User} from 'src/entities/User.ts';
            import {Album} from 'src/entities/Album.ts';
            import {Photos} from 'src/entities/Photos.ts';
            const connectionOptions: ConnectionOptions = {
                name: 'default',
                type: 'mysql',
                host: 'localhost',
                port: 3306,
                username: 'root',
                password: 'password',
                database: 'DemoDb',
                synchronize: false,
                logging: true,
                entities: [User, Album, Photos],
                migrations: ['src/migration/**/*.js'],
                subscribers: ['src/subscriber/**/*.js'],
              };
        
        

        终于

          const connectionName = 'default';
          const database = new Database();
          const dbConn: Connection = await database.getConnection(connectionName);
          const MspRepository = dbConn.getRepository(Msp);
          await MspRepository.delete(mspId);
        

        【讨论】:

          【解决方案6】:

          我在将getConnectionOptions 用于不同环境时遇到此错误。使用一个数据库进行开发,另一个用于测试。这就是我修复它的方法:

          const connectionOptions = await getConnectionOptions(process.env.NODE_ENV);
          await createConnection({...connectionOptions, name:"default"});
          

          我使用getConnectionOptions 来获取当前环境的连接,为了成功,您必须将ormconfig.json 更改为一个数组,其中包含您想要的不同环境的键“名称”,如下所示:

          [
          {
              "name" : "development",
              "type": "USER",
              "host": "localhost",
              "port": 5432,
              "username": "postgres",
              "password": "PASS",
              "database": "YOURDB"
          },
          {
              "name" : "test",
              "type": "USERTEST",
              "host": "localhost",
              "port": 5432,
              "username": "postgres",
              "password": "PASSTEST",
              "database": "YOURDBTEST"
          }
          ]
          

          现在connectionOptions 将包含当前环境的连接参数,但是将其加载到createConnection 会引发您指出的错误。将 connectionOptions 名称更改为“默认”解决了该问题。

          【讨论】:

            【解决方案7】:

            如果以后有其他人遇到这个问题,请检查一下以防万一:

            我不小心做了“user.save()”而不是“userRepo.save(user)”。

            (当然还有像这样初始化连接:

            const userRepo = getConnection(process.env.NODE_ENV).getRepository(User))

            【讨论】:

              【解决方案8】:

              如果有人使用 getRepository() 的 Express Router,请检查以下代码

              const router = Router();
              
              router.get("/", async function (req: Request, res: Response) {
                // here we will have logic to return all users
                const userRepository = getRepository(User);
                const users = await userRepository.find();
                res.json(users);
              });
              
              router.get("/:id", async function (req: Request, res: Response) {
                // here we will have logic to return user by id
                const userRepository = getRepository(User);
                const results = await userRepository.findOne(req.params.id);
                return res.send(results);
              });
              

              只要确保在每条路线上都拨打getRepository(),就像萨拉斯艾莉亚在接受的答案中所说的那样。

              【讨论】:

              • 谢谢,它有效。但是在每条路由中调用 getRepository 并不是一个好办法。
              【解决方案9】:

              对于那些正在寻找其他答案的人,请查看此内容。

              就我而言,问题是因为我在我的数据库配置中传递了name

              export const dbConfig = {
                  name: 'myDB',
                  ...
              }
              
              await createConnection(dbConfig) // like this
              

              因此,唯一知道的连接服务器是myDB 而不是default

              同时,在我的服务中,没有name 注入存储库,这将回退到default。 (结果服务会寻找default 连接)

              @Service() // typedi
              export class Service {
                  constructor(
                      // inject without name -> fallback to default
                      @InjectRepository() private readonly repository
                  ) {}
              }
              

              作为修复,我在我的数据库配置中删除了 name 属性。

              或者您可以将myDB 作为InjectRepository 的参数传递给@InjectRepository('myDB'),无论哪种方式都可以。

              【讨论】:

                【解决方案10】:

                虽然Saras Arya提供了正确答案,但我也遇到了同样的错误

                ConnectionNotFoundError:找不到连接“默认”。

                因为我的typeORM 实体确实有一个@Entity() 装饰器,并且它扩展了BaseEntity

                两个人不能住在一起。

                【讨论】:

                • 如果您使用的是活动记录模式,则不会:github.com/typeorm/typeorm/blob/master/docs/…
                • Ut 在我使用ts-node 启动它并在转译后开始失败时工作正常。 two can't live together 是什么意思?你能详细说明一下吗?
                【解决方案11】:

                赞成的答案不一定正确,如果您不指定连接名称,它将默认为“默认”。

                const manager = getConnectionManager().get('your_orm_name');
                const repository = manager.getRepository<AModel>(Model);
                

                【讨论】:

                • 我试过那个connectionManager,但我得到了同样的错误。
                【解决方案12】:

                您正在尝试在未建立连接的情况下创建存储库或管理器。

                尝试在函数中执行此const shopkeeperRepository = getRepository(Shopkeeper);。它会工作

                【讨论】:

                  猜你喜欢
                  • 2019-09-08
                  • 2020-11-25
                  • 2020-12-03
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-02-19
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多