29

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

我有以下用户实体:

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

9 回答 9

43

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

@Module({
  imports: [TypeOrmModule.forFeature([Users, ...])],  <--- Importing the entity!
  controllers: [...],
  providers: [...],
  exports: [...],
})
于 2020-06-10T14:21:52.020 回答
27

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

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

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

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

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

于 2019-07-12T02:50:18.220 回答
13

我遇到了同样的问题。

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

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

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

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

在一个文件中,我有

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

另一个我有

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

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

于 2020-11-16T22:23:53.653 回答
8

在我的项目中,TypeORM 初始化如下:

import { createConnection } from 'typeorm';

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

  // ... More options
})

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

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

于 2020-11-18T20:35:02.077 回答
7

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

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

于 2021-08-03T14:49:30.537 回答
1

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

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

于 2020-02-21T01:59:53.470 回答
1

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

于 2022-02-04T13:54:49.170 回答
0

我遇到过同样的问题。我正确地将 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,
    ...,
于 2021-09-18T19:39:12.420 回答
0

在我的项目中删除 dist 解决了这个问题。

于 2022-02-27T04:02:04.870 回答