TypeORM OneToMany 导致 "ReferenceError: 无法访问 '<Entity>'初始化之前" [英] TypeORM OneToMany causes "ReferenceError: Cannot access '<Entity>' before initialization"

查看:187
本文介绍了TypeORM OneToMany 导致 "ReferenceError: 无法访问 '<Entity>'初始化之前"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体:用户习惯.一个用户可以创建多个习惯,因此我在用户上使用 OneToMany 关系(分别在习惯上使用 ManyToOne).

I have two entities: User and Habit. A user can create multiple Habits, thus I use a OneToMany relation on the User (and ManyToOne on the Habit, respectively).

import {Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, BeforeInsert, BeforeUpdate, OneToMany} from "typeorm";
import * as bcrypt from "bcryptjs";
import { Habit } from "../habits/habits.entity";

@Entity()
export class User {
    @PrimaryGeneratedColumn("uuid")
    id: string;

    @Column()
    name: string;

    @Column()
    email: string;

    @Column()
    password: string;

    @OneToMany(type => Habit, habit => habit.author)
    habits: Habit[];

    @CreateDateColumn()
    dateCreated: Date;

    @UpdateDateColumn()
    dateUpdated: Date;

    @BeforeInsert()
    @BeforeUpdate()
    async hashPassword(): Promise<void> {
        this.password = await bcrypt.hash(this.password,10);
    }

    async comparePassword(password: string): Promise<boolean> {
        return bcrypt.compare(password, this.password);
    }

    constructor(props: any) {
        Object.assign(this, props);
    }
}

习惯实体

import {Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn, ManyToOne} from "typeorm";
import { User } from "../users/users.entity";

@Entity()
export class Habit {
    @PrimaryGeneratedColumn("uuid")
    id: string;

    @Column()
    name: string;

    @Column({ nullable: true})
    description?: string;

    @ManyToOne(type => User, user => user.habits)
    author: User;

    @CreateDateColumn()
    dateCreated: Date;

    @UpdateDateColumn()
    dateUpdated: Date;

    constructor(props: Partial<Habit>) {
        Object.assign(this, props);
    }
}

问题

在设置上述关系时,我收到以下错误

Problem

When setting up the above relation I receive the following error

WARNING in Circular dependency detected:
apps\api\src\habits\habits.entity.ts -> apps\api\src\users\users.entity.ts -> apps\api\src\habits\habits.entity.ts

WARNING in Circular dependency detected:
apps\api\src\users\users.entity.ts -> apps\api\src\habits\habits.entity.ts -> apps\api\src\users\users.entity.ts


/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "User", function() { return User; });
                                                                                               ^
ReferenceError: Cannot access 'User' before initialization
    at Module.User (...\dist\apps\api\main.js:1782:96)
    at Module../apps/api/src/habits/habits.entity.ts (...\dist\apps\api\webpack:\apps\api\src\habits\habits.entity.ts:42:13)
    at __webpack_require__ (...\dist\apps\api\webpack:\webpack\bootstrap:19:1)
    at Module../apps/api/src/users/users.entity.ts (...\dist\apps\api\main.js:1790:79)
    at __webpack_require__ (...\dist\apps\api\webpack:\webpack\bootstrap:19:1)
    at Module../apps/api/src/config/db-config.service.ts (...\dist\apps\api\main.js:1038:77)
    at __webpack_require__ (...\dist\apps\api\webpack:\webpack\bootstrap:19:1)
    at Module../apps/api/src/config/config.module.ts (...\dist\apps\api\main.js:978:76)
    at __webpack_require__ (...\dist\apps\api\webpack:\webpack\bootstrap:19:1)
    at Module../apps/api/src/app/app.module.ts (...\dist\apps\api\main.js:147:79)

注意

我使用 Nx 并创建了一个 NestJS 应用程序.TypeOrm 版本是 "^0.2.22",@nestjs/typeorm 版本是 "^6.2.0"

Note

I use Nx and have created a NestJS app. The TypeOrm version is "^0.2.22" and the @nestjs/typeorm version is "^6.2.0"

我的tsconfig如下:

{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2018", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@awhile/contracts": ["libs/contracts/src/index.ts"],
      "@awhile/ui": ["libs/ui/src/index.ts"]
    }
  },
  "exclude": ["node_modules", "tmp"]
}

我尝试使用 ManyToMany 关系并且它奏效了.此外,在单独的 NestJS 应用程序(没有 Nx)上,我无法重现此参考错误.在 tsconfig.json 中更改 ECMAScript 目标 版本也不起作用.

I have tried to use a ManyToMany relation and it worked. Also, on a separate NestJS app (without Nx) I cannot reproduce this reference error. Changing the ECMAScript target version in the tsconfig.json also did not work.

这两个实体仅在其服务中使用,不会在其他任何地方实例化.

Both entities are only used in their services and are not instantiated anywhere else.

感谢您的帮助.提前致谢.

I appreciate any help. Thank you in advance.

推荐答案

我通过在将 TypeORM 配置加载到 NestJS 时使用 autoLoadEntities: true 解决了这个问题.请注意,这是 NestJS 的额外内容,因此如果您使用的是 ormconfig.json,则不会应用此属性.

I solved this by using autoLoadEntities: true when loading the TypeORM config to NestJS. Note that this is a NestJS extra, so if you are using ormconfig.json this property won't be applied.

autoLoadEntities 文档在这里:https://docs.nestjs.com/techniques/database#auto-load-entities

autoLoadEntities documentation here: https://docs.nestjs.com/techniques/database#auto-load-entities

更新 04/10/2020

我一直有同样的关系问题.我发现的另一个解决方案,即使它违反了某些标准,也是将所有实体添加到 1 个文件中.将它们导出到那里并在需要的地方导入.

I kept having the same issue with relations. Another solution I found, even if it breaks some standards is to add all the Entities into 1 file. Export them there and import them where needed.

请记住,声明类的顺序很重要.

Keep in mind that the order in which the classes are declared matters.

这篇关于TypeORM OneToMany 导致 &quot;ReferenceError: 无法访问 '&lt;Entity&gt;'初始化之前"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆