'Entity metadata for Role#users was not found

Trying to make OneToMany and ManyToOne relationship with TypeORM but I get this error, I don't know what's wrong with my code.

I have the following User entity:

import { BaseEntity, Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { Field, ID, ObjectType } from 'type-graphql';

import { Role } from './';

@ObjectType()
@Entity()
export class User extends BaseEntity {
  @Field(() => ID)
  @PrimaryGeneratedColumn()
  public id: number;

  @Field()
  @Column('text', { unique: true })
  public userName: string;

  @Column()
  public password: string;

  @Field()
  @Column('boolean', { default: true })
  public isActive: boolean;

  @ManyToOne(() => Role, role => role.users)
  @Field(() => Role, { nullable: true })
  public role: Role;
}

Role entity:

import { BaseEntity, Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
import { Field, ID, ObjectType } from 'type-graphql';

import { User } from '.';

@ObjectType()
@Entity()
export class Role extends BaseEntity {
  @Field(() => ID)
  @PrimaryGeneratedColumn()
  public id: number;

  @Field()
  @Column('text', { unique: true })
  public name: string;

  @OneToMany(() => User, user => user.role, { lazy: false })
  @Field(() => [User], { nullable: true })
  public users: User[];
}

However I keep getting this error

(node:4541) UnhandledPromiseRejectionWarning: Error: Entity metadata
for Role#users was not found. Check if you specified a correct entity
object and if it's connected in the connection options. [1]     at
/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:571:23
[1]     at Array.forEach (<anonymous>) [1]     at
EntityMetadataBuilder.computeInverseProperties
(/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:567:34)
[1]     at
/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:80:74
[1]     at Array.forEach (<anonymous>) [1]     at
EntityMetadataBuilder.build
(/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:80:25)
[1]     at ConnectionMetadataBuilder.buildEntityMetadatas
(/node_modules/typeorm/connection/ConnectionMetadataBuilder.js:57:141)
[1]     at Connection.buildMetadatas
(/node_modules/typeorm/connection/Connection.js:494:57)
[1]     at Connection.<anonymous>
(/node_modules/typeorm/connection/Connection.js:126:30)
[1]     at step
(/node_modules/tslib/tslib.js:136:27) [1]
(node:4541) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
not handled with .catch(). (rejection id: 1) [1] (node:4541) [DEP0018]
DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.


Solution 1:[1]

I am using NestJS with PostgreSQL and I had the same issue. The problem was by me is that I forgot to import the entity in the module with the TypeOrmModule.forFeature function.

@Module({
  imports: [TypeOrmModule.forFeature([Users, ...])],  <--- Importing the entity!
  controllers: [...],
  providers: [...],
  exports: [...],
})

Solution 2:[2]

This just means that your entities are either not loading, or are loading incorrectly

You need to fix the loading of your entities. Entities will usually be loaded from the ormconfig.js file

Just create a file ormconfig.js and type something like this, emphasis on the entities

module.exports = {
  "name": "default",
  "type": "mongodb",
  "host": "localhost",
  "port": "27017",
  "username": "root",
  "password": "",
  "database": "rocketlaunches",
  "entities": [
    __dirname + "entities/**/*.entity.ts"
  ]
}

Now obviously, you would load your entities from wherever they are on your project

Solution 3:[3]

I ran into the same issue.

TypeORM is very difficult to debug with args and meta data classes/collections all over the place. After many hours I was able to figure it out.

So this relationship is failing because EntityMetadataBuilder.ts is trying to tie the type of the ManyToOne column with a known entity type using "===".

var inverseEntityMetadata = entityMetadatas.find(function (m) { return m.target === relation.type || (typeof relation.type === "string" && m.targetName === relation.type); });

Looking at relation.type I could see that it is the same "type" as m.target however they were not pointing to the same reference of the defined type. It seemed to me as if my related class was being loaded by node more than once. After reading about how node caches modules I was able to fix my problem by making sure all of my import statements were referencing the same file including uppercase/lowercase letters in the string.

In one file I had

import { Transaction } from "./transaction";

and the other I had

import { Transaction } from "./Transaction";

Notice the uppercase "t". After replacing with a lowercase "T" everything worked as expected.

Solution 4:[4]

If you still have the issue after applying the other solutions presented here. Check if your entities have the @Entity() decorator. I was missing this and after adding it it solved the issue.

Also adding autoLoadEntities: true in the connection options was needed.

Solution 5:[5]

In my project TypeORM is initialized like this:

import { createConnection } from 'typeorm';

const conn = await createConnection({
  // Make sure to specify all entities here
  entities: [User, Role],

  // ... More options
})

Just need to make sure that entities lists all your entities.

(This is the alternative if you're not using ormconfig.js to specify entities.)

Solution 6:[6]

My problem was that I was using node-ts to run only the typescript files for my project. However, my build still emitted .js files that were ignored/hidden. I don't know why, but cleaning out the *.js and *.js.map compiled files worked. What's strange is my ormconfig only specifies .ts files.

I recommend adding the "noEmit": true to tsconfig.json compiler options to prevent any future headaches with a similar approach.

Solution 7:[7]

I had this problem because I accidentally deleted my RoleModule "role.module.ts". When I recreated the module the problem was easelly solved.

Solution 8:[8]

In my project deleting dist solves the issue.

Solution 9:[9]

For my case, I was missing the @Entity() on top of my class, check if all your classes have the @Entity() decorator

Solution 10:[10]

After trying the solutions above ( delete the dist, put the @Entity() decorator, look for maybe a wrong import in the case of capital letter in one file and not in the other), I just disable the autoLoadEntities and import manually all of my entities in the entities field.

NB : In the config.ts file, I got a class AppConstant in which all of my useful constants are declared Like DB_CONFIG shown in this pic.

config.ts enter image description here

And in the app.module.ts, I make this :

In sum, It's just an typeOrm import error so this is what I did to solve this issue

app.module.ts enter image description here

Solution 11:[11]

I had the same issue. I correctly had place the TypeOrm.forFeature([Denom]) in the DenomModule, but I was missing the entity in the main module:

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: "postgres",
      host: "localhost",
      port: 5432,
      username: "postgres",
      password: "postgres",
      database: "testnestjs",
      entities: [.., Denom],
      synchronize: true
    }),
    DenomModule,
    ...,

Solution 12:[12]

I keep doing the same mistake over and over. In typeorm config I specify to look for dist/**/*.model.js files.

But every now and then I have this brilliant idea to start using *.entity.ts suffix, resulting in the above error.

Renaming file to xx.model.ts fixes it.

Solution 13:[13]

I faced this problem, in my case, the solution is to remove the dist folder inside the server

Solution 14:[14]

in my case, I solved it by adding the Role entity. to the entity array in the main app.module class. I initially forgot to add it.

TypeOrmModule.forRoot({
  type: process.env.DB_TYPE as any,
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT),
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  entities: [User, Role],
  synchronize: true,