typeorm getConnection() cannot find "default" connection

Viewed 912

I have a NX mono repo project where I want to use typeorm. The config file ormconfig.json is in the workspace root (same package.json folder) and this is the content:

{
    "name": "default",
    "type": "sqlite",
    "database": "data/db.sql",
    "logging": true,
    "entities": ["libs/database/src/entities/*.entity.{ts,js}"],
    "migrations": ["libs/database/src/migrations/*.{ts,js}"],
    "cli": {
        "entitiesDir": "libs/database/src/entities",
        "migrationsDir": "libs/database/src/migrations",
        "subscribersDir": "libs/database/src/subscribers"
    }
}

As you can see the entities are in a database lib.

This configuration works fine for the migrations but when I try to call getConnection() (from anywhere, for example a node app inside the same workspace) I get the error ConnectionNotFoundError: Connection "default" was not found.

1 Answers

I have been utilizing mono repos for my projects too. From my experience, after searching for the same issue too before some months, I found out that you should place the ormconfig.json file in the top directory of your project. For example, if your directory looks like this:

project/
    packages/
        backend/
        common/
        frontend/
  • And your ormconfig.json file is located in the project/packages/backend/ directory, then you should move it to the at the top or parent directory, which is project/.

  • Make sure also that your Entities or Migrations show the correct location of your entities folder in the directory path/tree. As I see you are first build and compile your code and then run it with node. So, if that is the scenario, and you do not use tools like ts-node, then you are correct to place the Entities or Migrations directory to point at the lib / dist / build folder.

  • I found also helpful to use this utility function from Ben Awad, to connect TypeORM with my database. I hope it helps you too!

Related