【发布时间】:2022-01-21 14:53:02
【问题描述】:
我需要在 Nest.js 中将 CRM API 与我的服务集成。不幸的是,他们要求我实现他们的接口以使用自定义持久层,在我的例子中是 Mongo。因为我需要实例化生成的类,所以我不能像往常一样注入模型,所以我尝试在类成员变量上使用它。但是,这会导致成员变量未定义的错误。
这是我的猫鼬模型:
export type ZohoTokenDocument = ZohoToken & Document;
@Schema({ timestamps: true })
export class ZohoToken {
@Prop()
name: string;
@Prop({ type: String, length: 255, unique: true })
user_mail: string;
@Prop({ type: String, length: 255, unique: true })
client_id: string;
@Prop({ type: String, length: 255 })
refresh_token: string;
@Prop({ type: String, length: 255 })
access_token: string;
@Prop({ type: String, length: 255 })
grant_token: string;
@Prop({ type: String, length: 20 })
expiry_time: string;
}
export const ZohoTokenSchema = SchemaFactory.createForClass(ZohoToken);
这是我根据第 3 方 API 的要求创建的自定义类:
export class ZohoStore implements TokenStore {
@InjectModel(ZohoToken.name)
private readonly tokenModel: Model<ZohoTokenDocument>;
async getToken(user, token): Promise<any> {
const result = await this.tokenModel.findOne({ grant_token: token });
return result;
}
...
在我的服务中,我只是将这个类实例化为new ZohoStore(),在稍后调用getToken() 方法之前它工作正常。
产生的错误是:"nullTypeError: Cannot read property 'findOne' of undefined",,这对我来说意味着tokenModel 没有被实例化。知道如何将模型注入此类而不将其放入构造函数中,否则我无法使用服务中的零参数构造函数对其进行实例化?
【问题讨论】:
标签: typescript mongoose nestjs zoho