typeorm: Error: Entity metadata was not found

// conversation_pairs.ts

@Entity()
export class ConversationPairs {

  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(type => Users, user_id => user_id.conversation_pairs, {
    cascadeRemove: true,
    nullable: false
  })
  user_id: Users;

  @ManyToOne(type => Agents, agent_id => agent_id.conversation_pairs, {
    cascadeRemove: true,
    nullable: false
  })
  agent_id: Agents;
}

// user.ts

@Entity()
export class Users {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToMany(type => ConversationPairs, conversation_pairs => conversation_pairs.user_id)
  conversation_pairs: ConversationPairs[];
}

// agent.ts

@Entity()
export class Agents {

  @PrimaryGeneratedColumn()
  id: number;

  @OneToMany(type => ConversationPairs, conversation_pairs => conversation_pairs.agent_id)
  conversation_pairs: ConversationPairs[];
}

I have these 3 files and getting this error when I start my app.

Error: Entity metadata for ConversationPairs#user_id was not found.
    at /Users/xuanrong/Sites/calllevels/dbs-chat/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:272:27
    at Array.forEach (native)
    at /Users/xuanrong/Sites/calllevels/dbs-chat/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:269:38
    at Array.forEach (native)
    at EntityMetadataBuilder.build (/Users/xuanrong/Sites/calllevels/dbs-chat/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:268:25)
    at EntityMetadataBuilder.buildFromMetadataArgsStorage (/Users/xuanrong/Sites/calllevels/dbs-chat/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:152:21)
    at Connection.buildMetadatas (/Users/xuanrong/Sites/calllevels/dbs-chat/node_modules/typeorm/connection/Connection.js:552:18)
    at Connection.<anonymous> (/Users/xuanrong/Sites/calllevels/dbs-chat/node_modules/typeorm/connection/Connection.js:174:30)
    at step (/Users/xuanrong/Sites/calllevels/dbs-chat/node_modules/typeorm/connection/Connection.js:32:23)
    at Object.next (/Users/xuanrong/Sites/calllevels/dbs-chat/node_modules/typeorm/connection/Connection.js:13:53)

Not sure what to do, need some help on this.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 28
  • Comments: 66 (10 by maintainers)

Commits related to this issue

Most upvoted comments

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 { Category } from "./models/category";

and the other I had

import { Category } from "./Category";

Notice the uppercase “C”. After replacing with a lowercase “c” everything worked as expected.

Conclusion: this error happening when you have misspelled your entity name, misspelled import paths or did not include your entity in connection configuration.

I had the same issue. I was importing and re-exporting all my entities in src/entity/index.ts, e.g.

// src/entity/index.ts
export { Task } from './Task';
export { Unit } from './Unit';
export { User } from './User';

and then importing them from that index file to reference them in other entities, e.g.

// src/entity/User.ts
import {
  Task,
  Unit,
} from '.';

Rather than changing my import references like @michaelonubogugauge suggested, I just changed my ormconfig file from

entities: [ 'src/entity/**/*.ts' ]

to

entities: [ 'src/entity/index.ts' ]

which solved the problem for me.

I can confirm @tomkroening solution. Importing the same Entity from a different path will cause the following error:

Error: Entity metadata for Category#users was not found. Check if you specified a correct entity object, check its really entity and its connected in the connection options.

This error is somewhat misleading as it suggests that you haven’t imported your entities. While that can be a valid reason for this, the other can be above mentioned import path issue pointed out by @tomkroening.

How solve this error most effectively? You can do the following steps:

First lets understand from where the error is coming from. TypeORM says that it cannot find the Category#users relation. So the problem is with the User entity in this case. Category was found successfully but TypeORM was not able to find the related User entity.

So what you have to search for is the import { User code snippet, and check if all the import paths point to the same location.

Ok so now we can ask what is exactly a same location? Two path is exactly the same if they point to the same location when resolved by the filesystem.

A few example:

Lets assume we have the following tree structure:

 src
├─ services
│   └── folderx
│      └── foldery
│         └── xy.service.ts
└─ entities
│   ├── index.ts
│   └─ user.entity.ts
└─ xy.ts

Where index.ts re-export user.entity.ts (aka it’s a barell file.)

Then importing user.entity.ts from xy.service.ts as ../../../entities is resolved as the same as importing the user.entity.ts from xy.ts as ./entities, while importing it as ./entities/user.entity would not resolve as the same because it’s points to ./entities/user.entity.ts file instead of ./entities/index.ts file.

In this case, I solved by change the ormconfig.json content

.
.
  "entities": [
     "dist/entity/**/*.ts"
  ],

to

.
.
  "entities": [
     "dist/entity/**/*.js"
  ],

I came across this error when I forgot to decorate my newly created entity using “Entity” decorator.

If you are using TypeORM with NestJS, do not forget to add the @Entity() decorator. Failure to do so will also trigger this error.

I had this one bugging me for a while, a bit like @geabenitez I had forgot the @entity() annotation.

I have the same problem, but my conclusins is different:

I have such structure for my two entities:

import { Entity, ManyToMany, JoinTable } from 'typeorm';
import { Role } from '../role';

@Entity()
export class User {
  @ManyToMany(type => Role, role => role.users)
  @JoinTable({ name: 'user_roles' })
  roles: Role[];
}
import { ManyToMany } from 'typeorm';
import { User } from '../user/user.entity';

@Entity()
export class Role {
  @ManyToMany(type => User, user => user.roles)
  users: User[];
}

This two entites does not work together, but if I remove any of relation from Role (role.users) or from User (user.roles) entity - all works correctly. Perhaps, something wrong not only with filesistem paths, but also with circular dependecies

If you’re using NestJS, you may have forgotten to add the entity to the TypeOrmModule.forFeature()

Hello For me it was to forget to add the () at the end of @Entity()

@NoNameProvided @tomkroening Thank you so much. Your thorough explanation helped me to resolve my issue. For me, it was basically changing an import reference from:

import {Entity} from './' \\via index.ts

to

import {Entity} from './Entity'

Basically setting an explicit reference to the entity. Thanks again.

entities: [__dirname + '/../**/*.entity.{js,ts}'],

For the record, I experienced the same problem. Went through all imports to ensure they were correct. Problem remained. Turned out it was because I used ts-node to launch the app. Worked fine after a tsc build and normal node start.

I also got that same error when i accidentally forgot to decorate the entity class with @Entity() decorator.

ts-node doesn’t compile the source files so it was looking at the compiled entity path.

I fixed the issue by adding both the compiled and raw entity paths.

const entities = [
  ".next/server/database/entity/**/*.js",
  "server/database/entity/**/*.ts"
];

I notice also that using custom paths breaks the references to entities

{
  "compilerOptions": {
    "paths": {
      "@user/*": [
        "src/user/*"
      ],
      "@common/*": [
        "src/common/*"
      ],
    }
  },
}

This one does not work :

import { User } from "@user/entity/user.entity";

@Entity()
export class Registration extends Resource {
  @OneToOne(type => User)
  @JoinColumn()
  user: User
}

This one works…

import { User } from "./user.entity";

@Entity()
export class Registration extends Resource {
  @OneToOne(type => User)
  @JoinColumn()
  user: User
}

The user.module declares the entities with the custom path :

import { Registration } from '@user/entity/registration.entity';
import { User } from '@user/entity/user.entity';

@Module({
  imports: [
    TypeOrmModule.forFeature([
      Registration,
      User
    ])
  ],
})
export class UserModule { }

Is it possible to re-open this issue in order to fix the Type check for entity metadata management ?

Because I don’t know how it will behave with entities inside another module (e.g. the @common module)

@tomkroening thank you so much for this! i would have never guessed this.

Sometimes, you just need to delete dist folder and to retry.

  • Check that entity is in the correct folder : @masakiando , and if it does not work ,you can also use index.ts But sometimes you just need to need to delete the dist folder and try again.
  • Delete dist folder
  • Ctrl+C
  • Yes
  • npm run start:dev

😃

to me I forgot to add @Entity("myEntityName") in my class

I got the following error:

Error: Entity metadata for AccountEntity#owner was not found. Check if you specified a correct entity object and if it’s connected in the connection options.

And I was very convinced that my setup was correct:

AccountEntity.ts

// ...
@ManyToOne(() => OwnerEntity, owner => owner.accounts, {onDelete: 'CASCADE'})
owner!: OwnerEntity;
// ...

OwnerEntity.ts

// ...
@OneToMany(() => AccountEntity, account => account.owner)
accounts!: AccountEntity[];
// ...

initDatabase.ts

Object.assign(connectionOptions, {
  entities: [
    AccountEntity,
    OwnerEntity
  ],
  logging: false,
  migrations: [],
  subscribers: [],
  synchronize: true,
});

After half an hour of debugging (luckily not hours!) I noticed that I was missing the @Entity() annotation in my OwnerEntity class. 🙈 So be smarter than me and don’t make the same mistake. 😄

I stick to this error again and again on projects losing so much time looking for typos or paths that not exactly match from one file to another… plus the fact that the error message provides poor information, that’s quite BS…

For me, this issue happened because I forgot to add @Entity at the top of my class 🤦‍♂️ so don’t forget to check if your issue is the same.

In this case, I solved by change the ormconfig.json content

.
.
  "entities": [
     "dist/entity/**/*.ts"
  ],

to

.
.
  "entities": [
     "dist/entity/**/*.js"
  ],

This solves my problem, Changing TS to JS

I had the same issue. I was importing and re-exporting all my entities in src/entity/index.ts, e.g.

// src/entity/index.ts
export { Task } from './Task';
export { Unit } from './Unit';
export { User } from './User';

and then importing them from that index file to reference them in other entities, e.g.

// src/entity/User.ts
import {
  Task,
  Unit,
} from '.';

Rather than changing my import references like @michaelonubogugauge suggested, I just changed my ormconfig file from

entities: [ 'src/entity/**/*.ts' ]

to

entities: [ 'src/entity/index.ts' ]

which solved the problem for me.

thanks a lot. the problem was not file path as I was sure all of my import statements were referencing the same file. I exported all my entities from database.entites.ts file and edited ormconfig.json as follows "entities": [ "src/database.entities.ts" ],

I figured it out. Circular references between entities break types passed directly to decorators. This is why TypeORM uses futures (type => MyClass)

that was a problem in entity name

As @ngocketit mentioned, this may be unrelated to your entity file or files altogether. In my case, I have all of my entities in a single file (to avoid circular dependency issues with nx and NestJs), but this problem still happens if I am not importing the entities to the correct feature module.

For example, if you have the following two entities:

@Entity('products')
export class ProductEntity {
  @PrimaryGeneratedColumn()
  public readonly id: number;

  @OneToMany(
     type => OrderEntity,
     order => order.product
  )
  @JoinColumn()
  orders: OrderEntity[]
}

@Entity('orders')
export class OrderEntity {
  @PrimaryGeneratedColumn()
  public readonly id: number;

  @ManyToOne(
     type => ProductEntity,
     product => product.orders
  )
  @JoinColumn()
  product: ProductEntity
}

And in your feature module, your import looks like this:

imports: [TypeOrmModule.forFeature([ProductEntity])]

Even if you do not use OrderEntity explicitly within this feature module, you need to import it for the relationships to resolve correctly:

imports: [TypeOrmModule.forFeature([ProductEntity, OrderEntity])]

I got error when using relation in Entity like @ManyToOne @OneToMany. solved by import entity class directly from entity_name.ts file not from index or other place. ex: import { Branch } from '.' => import { Branch } from './branch'

I had the same issue. I was importing and re-exporting all my entities in src/entity/index.ts, e.g.

// src/entity/index.ts
export { Task } from './Task';
export { Unit } from './Unit';
export { User } from './User';

and then importing them from that index file to reference them in other entities, e.g.

// src/entity/User.ts
import {
  Task,
  Unit,
} from '.';

Rather than changing my import references like @michaelonubogugauge suggested, I just changed my ormconfig file from

entities: [ 'src/entity/**/*.ts' ]

to

entities: [ 'src/entity/index.ts' ]

which solved the problem for me.

This guy deserves a medal