Nestjs schema definition with mongoose:TypeError:Cannot read properties of undefined(阅读“name”)

thigvfpy  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(211)

我在一个NestJS应用程序中使用Mongoose,当我像那些代码一样定义我的模式时,我有一个错误。
为什么我有一个错误,如果我这样设置在协作模式中的引用

ref: Page.name,

字符串
但是如果我这样设置就没有错误了?

ref: 'Page',

**注意:**所有的schema定义都在同一个目录下,即“schemas”*。

这是我的页面模式看起来像

// Path: src/page/schemas/page.schema.ts

    import { Collaborator } from './collaborator.schema';

    @Schema({ timestamps: true, versionKey: false })
    export class Page {
      @Prop({ required: true, type: Number })
      owner_id: number;

      @Prop({ required: true, minlength: 3, maxlength: 100, trim: true })
      name: string;

      @Prop({ minlength: 3, maxlength: 250, trim: true })
      description: string;

      @Prop({
        type: [
          {
            type: mongoose.Schema.Types.ObjectId,
            ref: Collaborator.name,
            autopopulate: true,
          },
        ],
      })
      collaborators: Collaborator[];
    }

    export const PageSchema = SchemaFactory.createForClass(Page);


这是我的Collaborator模式,

// Path: src/page/schemas/collaborator.schema.ts

    import { Page } from './page.schema';

    export type CollaboratorDocument = HydratedDocument<Collaborator>;

    @Schema({ versionKey: false })
    export class Collaborator {
      @Prop({
        require: true,
        type: mongoose.Schema.Types.ObjectId,
        // there is an error if i set the ref like this
        ref: Page.name,
        /**
        but no error if i set like this
        ref: 'Page',
        */
      })
      page_id: mongoose.Schema.Types.ObjectId;

      @Prop({ required: true, type: Number })
      user_id: number;

      @Prop({ type: String, enum: ROLES, default: ROLES.MODERATOR })
      role: string;
    }

    export const CollaboratorSchema = SchemaFactory.createForClass(Collaborator);


控制台中的错误:

/src/page/schemas/page.schema.ts:42
    ref: Collaborator.name,
                      ^
TypeError: Cannot read properties of undefined (reading 'name')

mbzjlibv

mbzjlibv1#

这是由于PageCollaborator彼此之间是循环的,并且它们的每个导入都不能完全解析,直到另一个导入完成为止(耶循环导入)。您应该能够通过将ref设置为ref: () => Page.nameref: () => Collaborator.name来克服这个问题,以便它是对类型的惰性评估

相关问题