Ошибка TypeEr при попытке доступа к функции внутри класса ModelType - PullRequest
0 голосов
/ 30 июня 2019

Я работаю над приложением 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 Ответ

1 голос
/ 30 июня 2019

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