尝试访问ModelType类中的函数时发生TypeError

时间:2019-06-30 14:45:01

标签: node.js typescript mongoose-schema nestjs

我正在使用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());
    }
}

,并且我从提供程序类尝试访问toResponseObject(),但是它抛出了TypeError: orgs.toResponseObject is not a function。为什么提供程序类无法访问该功能?

1 个答案:

答案 0 :(得分:1)

Typegoose具有装饰器@instanceMethod,您可以使用它,以便在对普通对象进行序列化时,该函数也将被添加到类中。您可以将示例更改为

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 };
  }
}