Suroor Ahmmad
Suroor Ahmmad

Reputation: 1162

TypeError when trying to access function inside ModelType Class

I'm working on NestJS-MongoDB application, and using Typegoose for modeling. I have created model for the Org as below.

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

and from Provider class I'm trying to access toResponseObject() but it throws TypeError: orgs.toResponseObject is not a function. Why provider class unable to access that function?.

Upvotes: 0

Views: 446

Answers (1)

Dylan Aspden
Dylan Aspden

Reputation: 1692

Typegoose has a decorator @instanceMethod you can use so that when the plain objects get serialized the function will get added to the class as well. You could change your example to something like

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

Upvotes: 1

Related Questions