when running app.ts file i get the error EntityMetadataNotFoundError: No metadata for "user" was found

551 views Asked by At

i have this project on expressjs and I use typeorm and typescript. the problem is when i run project on develop mode (with app.ts), with the first request i get the error:

node_modules/src/data-source/DataSource.ts:427
        if (!metadata) throw new EntityMetadataNotFoundError(target)
                             ^
EntityMetadataNotFoundError: No metadata for "user" was found.

but everything is ok when i start the project from /dist/app.js.

i use es2020 as target and nodeNext as module and moduleResolution in tsconfig. and this is my package.json file: `

 "type": "module",
  "scripts": {
    "start": "tsc -p . && node dist/app.js",
    "start:prod": "node dist/app.js",
    "dev": "ts-node-esm app.ts --watch",
    "test": "mocha -r ts-node/register src/**/*.ts",
    "test-dev": "nodemon --watch . --ext ts --exec \"mocha -r ts-node/register src/**/*.ts\"",
    "build": "rimraf dist && tsc -p .",
}

`

and this is my typorm.config.ts file:

`

config();
const baseDir = 'dist/src';

export const appDataSource = new DataSource({
  type: 'postgres',
  host: process.env.POSTGRES_DB_HOST,
  port: Number(process.env.POSTGRES_DB_PORT),
  username: process.env.POSTGRES_DB_USER,
  password: process.env.POSTGRES_DB_PASSWORD,
  database: process.env.POSTGRES_DB_DATABASE,
  synchronize: false,
  logging: true,
  entities: [baseDir + '/**/entity/*.entity.js'],
  migrationsRun: true,
  migrations: [baseDir + '/migrations/*.js'],
});

`

i tried adding .ts to entities and migrations paths.

1

There are 1 answers

0
parisa rad On

to run code on production mode i had to add "type": "module" to my package.json file and also a bunch of more changes on my tsconfig file. but then i get that error on development mode. so apparently for some reasons .ts extensions in my typeorm.config file is not being recognized. so i had to use separate path to my entities and migration in my typeorm.config file. this seems to solve my issue for now.

config();
const entitiesString =
  process.env.NODE_ENV == 'production'
    ? 'dist/src/**/entity/*.entity.js'
    : 'src/**/entity/*.entity.ts';

const migrationString =
  process.env.NODE_ENV == 'production'
    ? 'dist/src/migrations/*.js'
    : 'src//migrations/*.ts';

export const appDataSource = new DataSource({
  type: 'postgres',
  host: process.env.POSTGRES_DB_HOST,
  port: Number(process.env.POSTGRES_DB_PORT),
  username: process.env.POSTGRES_DB_USER,
  password: process.env.POSTGRES_DB_PASSWORD,
  database: process.env.POSTGRES_DB_DATABASE,
  synchronize: false,
  logging: true,
  entities: [entitiesString],
  migrationsRun: true,
  migrations: [migrationString],
});