Home > Software engineering >  Nest.js Model Dependency Injection with Mongoose with no constructor
Nest.js Model Dependency Injection with Mongoose with no constructor

Time:12-20

I need to integrate a CRM API with my service in Nest.js. Unfortunately, they require I implement their interface to use a custom persistence layer, in my case, Mongo. Since I'll need to instantiate the resulting class, I can't inject the model as I normally would so I tried using this on the class member variable instead. However, this results in an error that the member variable is undefined.

This is my mongoose model:

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

This is the custom class I'm creating as required by the 3rd party 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;
  }
...

And in my service, I'm just instantiating this class as new ZohoStore(), which works fine until the getToken() method is called later.

The resulting error is: "nullTypeError: Cannot read property 'findOne' of undefined",, which to me means the tokenModel is not being instantiated. Any idea how I can get my model injected into this class without putting it in the constructor, otherwise I can't instantiate it with a zero-arg constructor from my service?

CodePudding user response:

If you're trying to use Nest DI system, then you just can't call new ZohoStore() by yourself because Nest has no chance to instantiate ZohoStore's dependencies.

You'll need to register it as a provider in some NestJS module and then retrive the instance created by NestJS if you want to.

  • Related