39

我将 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',
      ]
    })

当然,我的常数是正确的。有任何想法吗 ?

4

12 回答 12

34

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

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

于 2018-05-26T12:36:49.807 回答
10

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

const manager = getConnectionManager().get('your_orm_name');
const repository = manager.getRepository<AModel>(Model);
于 2019-09-24T14:51:40.103 回答
4

我们正在使用和使用 packagelerna中库中的代码。AB

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

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

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

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

于 2021-01-04T17:01:52.363 回答
3

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

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

(当然上面初始化连接是这样的:

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

于 2020-08-25T07:01:08.763 回答
2

如果有人使用 Express 路由器getRepository(),请检查下面的代码

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()像萨拉斯艾莉亚在接受的答案中所说的那样拨打每条路线。

于 2020-06-10T13:30:25.750 回答
2

我按照以下方法创建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);
于 2020-12-16T05:23:13.643 回答
1

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

就我而言,问题是因为我传入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或者您可以作为参数传递InjectRepositorylike @InjectRepository('myDB'),无论哪种方式都有效。

于 2019-10-07T06:35:08.733 回答
0

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为“默认”解决了这个问题。

于 2020-11-17T11:27:35.980 回答
0

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

Windows相关原因。

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

于 2020-12-31T21:49:58.733 回答
0

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

基本上,当我们创建一个外部包时——TypeORM 会尝试获取“默认”连接选项,但如果未找到,则会引发错误:

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

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

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(); 
 }

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

  • 外部 NPM 包:
  • 上述包的消费者:nest-typeorm-postgre(具体文件-package.json , src/countries/countries.service.ts & countries.module.ts
于 2021-02-12T15:02:10.743 回答
0

就我而言,我有一组多个连接,而不仅仅是一个。你有 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...
于 2021-07-15T02:49:27.720 回答
-1

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

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

由于我的typeORM实体确实有一个@Entity()装饰器并且它已经扩展了BaseEntity

两个人不能住在一起。

于 2019-01-08T13:11:58.503 回答