【问题标题】:Entity metadata for Role#users was not found找不到 Role#users 的实体元数据
【发布时间】:2019-11-03 16:37:30
【问题描述】:

试图与 TypeORM 建立 OneToManyManyToOne 关系但我收到此错误,我不知道我的代码有什么问题。

我有以下用户实体:

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

角色实体:

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[];
}

但我不断收到此错误

(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.

【问题讨论】:

  • 当您忘记在其中一个实体上添加 @Entity 注释时,“未找到实体元数据”也会显示。实体还必须在连接设置的“实体”部分中声明(参见@Martin Konicek 的回答)。

标签: typeorm typegraphql


【解决方案1】:

我在 PostgreSQL 中使用 NestJS,我遇到了同样的问题。问题出在我身上,我忘记使用 TypeOrmModule.forFeature 函数在模块中导入实体。

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

【讨论】:

  • 你先生,应该获得奖牌
【解决方案2】:

这只是意味着您的实体要么没有加载,要么加载不正确

您需要修复实体的加载。实体通常会从ormconfig.js 文件中加载

只需创建一个文件 ormconfig.js 并输入类似这样的内容,强调实体

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

现在显然,您可以从项目中的任何位置加载实体

【讨论】:

  • 好答案,提醒我检查一下 *.entity.ts 文件名,Thinks。
  • 认为不需要完整路径。看到 __dirname 让我清醒了很多。
【解决方案3】:

我遇到了同样的问题。

TypeORM 很难在到处使用 args 和元数据类/集合进行调试。几个小时后,我终于弄明白了。

所以这种关系失败了,因为 EntityMetadataBuilder.ts 试图使用“===”将 ManyToOne 列的类型与已知实体类型联系起来。

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

查看relation.type 我可以看到它与m.target 的“类型”相同,但是它们没有指向已定义类型的相同引用。在我看来,好像我的相关类不止一次被节点加载。在阅读了节点如何缓存模块之后,我能够通过确保我的所有导入语句都引用同一个文件(包括字符串中的大写/小写字母)来解决我的问题。

在我的一个文件中

从“./transaction”导入{交易};

和我的另一个

从“./Transaction”导入{交易};

注意大写的“t”。用小写“T”替换后,一切都按预期工作。

【讨论】:

  • 调试并不难。如果您只是添加一个console.log(relation.type); console.log(entityMetadatas);,您会看到它在一个数组中查找[Function: Table],其值应包含target: [Function: Table](在将关系指定为函数的情况下)。如果 entityMetadatas 没有该目标的值,则 createConnection 中缺少该实体
【解决方案4】:

在我的项目中,TypeORM 是这样初始化的:

import { createConnection } from 'typeorm';

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

  // ... More options
})

只需确保entities 列出了您的所有实体。

(如果您不使用ormconfig.js 来指定实体,这是另一种选择。)

【讨论】:

    【解决方案5】:

    如果您在应用此处介绍的其他解决方案后仍有问题。检查您的实体是否有 @Entity() 装饰器。我错过了这个,添加后它解决了这个问题。

    还需要在连接选项中添加autoLoadEntities: true

    【讨论】:

      【解决方案6】:

      我的问题是我使用 node-ts 只为我的项目运行打字稿文件。但是,我的构建仍然发出被忽略/隐藏的 .js 文件。我不知道为什么,但是清理 *.js 和 *.js.map 编译文件是有效的。奇怪的是我的 ormconfig 只指定了 .ts 文件。

      我建议将"noEmit": true 添加到 tsconfig.json 编译器选项中,以防止将来使用类似方法出现任何问题。

      【讨论】:

        【解决方案7】:

        我遇到了这个问题,因为我不小心删除了我的 RoleModule “role.module.ts”。当我重新创建模块时,问题就轻松解决了。

        【讨论】:

        • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
        【解决方案8】:

        我遇到了同样的问题。我正确地将 TypeOrm.forFeature([Denom]) 放置在 DenomModule 中,但我缺少主模块中的实体:

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

        【讨论】:

          猜你喜欢
          • 2020-10-09
          • 1970-01-01
          • 2023-03-19
          • 2021-02-24
          • 2021-05-18
          • 2022-10-20
          • 2021-04-17
          • 1970-01-01
          • 2016-09-13
          相关资源
          最近更新 更多