我正在使用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
。为什么提供程序类无法访问该功能?
答案 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 };
}
}