尝试访问 ModelType 中的函数时出现 TypeError Class

TypeError when trying to access function inside ModelType Class

我正在开发 NestJS-MongoDB 应用程序,并使用 Typegoose 进行建模。我已经为组织创建了如下模型。

org.model.ts

export class Org extends Typegoose {

    @prop({ required: true })
    name: string;

    @prop({ required: true, unique: true, validate: /\S+@\S+\.\S+/ })
    email: string;

    @prop({ required: true, minlength: 6, maxlength: 12, match: /^(?=.*\d).{6,12}$/ })
    password: string;

    @prop({ required: true, unique: true })
    phone: number;

    toResponseObject(){
        const {name, email, phone } = this;
        return {name, email, phone };
    }
}

org.service.ts

@Injectable()
export class OrgService {
    constructor(@InjectModel(Org) private readonly OrgModel: ModelType<Org>) { }

    async findAll() {
        const orgs = await this.OrgModel.findOne();
        console.log(orgs);
        console.log(orgs.toResponseObject()); // Throws error here
        // return orgs.map(org => org.toResponseObject());
    }
}

并且来自提供商 class 我正在尝试访问 toResponseObject() 但它抛出 TypeError: orgs.toResponseObject is not a function。为什么提供商 class 无法访问该功能?

Typegoose 有一个装饰器 @instanceMethod,您可以使用它,这样当普通对象被序列化时,函数也会被添加到 class 中。您可以将示例更改为

import { instanceMethod } from 'typegoose';
// ...

export class Org extends Typegoose {

  @prop({ required: true })
  name: string;

  @prop({ required: true, unique: true, validate: /\S+@\S+\.\S+/ })
  email: string;

  @prop({ required: true, minlength: 6, maxlength: 12, match: /^(?=.*\d).{6,12}$/ })
  password: string;

  @prop({ required: true, unique: true })
  phone: number;

  @instanceMethod
  toResponseObject(){
    const {name, email, phone } = this;
    return {name, email, phone };
  }
}