Nestjs 模式定义与猫鼬:类型错误:无法读取未定义的属性(读取“名称”)

问题描述 投票:0回答:1

我在 NestJS 应用程序中使用 Mongoose,当我像这些代码一样定义架构时出现错误。

如果我像这样在协作模式中设置引用,为什么会出现错误

ref: Page.name,

但是如果我这样设置就不会出错?

ref: 'Page',

注意:所有模式定义都在同一目录中'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);


这是我的协作者架构的样子


    // 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')
mongoose nestjs mongoose-schema
1个回答
0
投票

这是因为

Page
Collaborator
彼此是循环的,并且它们的每个导入在另一个导入之前无法完全解决(是的循环导入)。您应该能够通过将
ref
设置为
ref: () => Page.name
ref: () => Collaborator.name
来克服这个问题,这样它就是类型的惰性评估

© www.soinside.com 2019 - 2024. All rights reserved.