找不到 Role#users 的实体元数据

Sou*_*ane 18 typeorm typegraphql

试图让OneToManyManyToOne与TypeORM关系,但我得到这个错误,我不知道什么是错我的代码。

我有以下用户实体:

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;
}
Run Code Online (Sandbox Code Playgroud)

角色实体:

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[];
}
Run Code Online (Sandbox Code Playgroud)

但是我不断收到此错误

(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.
Run Code Online (Sandbox Code Playgroud)

llo*_*ono 54

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

autoLoadEntities: true需要添加连接选项。


Dáv*_*oly 24

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

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

  • 先生,你应该获得一枚奖章 (4认同)

Off*_*ssu 22

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

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

只需创建一个文件ormconfig.js并键入这样的内容,重点放在实体上

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

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

  • 好的答案,提醒我检查 *.entity.ts 文件名,我想。 (2认同)

小智 9

我遇到了同样的问题。

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”中缺少该实体 (2认同)

小智 8

就我而言,我错过了@Entity()班级顶部的内容,请检查您的所有班级是否都有@Entity()装饰器


小智 6

我遇到了这个问题,就我而言,解决方案是删除服务器内的 dist 文件夹


Mar*_*cek 5

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

import { createConnection } from 'typeorm';

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

  // ... More options
})
Run Code Online (Sandbox Code Playgroud)

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

(如果您不ormconfig.js用于指定实体,则这是替代方法。)


小智 5

就我而言,我通过添加角色实体解决了这个问题。到主 app.module 类中的实体数组。我最初忘记添加它。

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,
Run Code Online (Sandbox Code Playgroud)