1

So my problem is I have models that is separated by one of our domain's types, and it has a lot of types which each one of em has a dedicated collection. As I know, we can inject the model in the service constructor like this way:

@InjectModel(ModelName.Job) private readonly jobModel: JobModel,

It is a bit messy to me to inject all of those collections in the constructor, and also they are not useful at the same time. So I wonder if I could load mongoose model dynamically inside the service's method using the our domain type as the key, more or less same as the module reference like this:

private getModelReference(reference: any) {
    return this.moduleReference.get(ModelName[reference]);
}

But, any other workarounds to load the model dynamically on the fly are appreciated.

fsevenm
  • 791
  • 8
  • 19

1 Answers1

1

It is technically possible to do. Using your code above you can do

private getModelReference(reference: any) {
  return this.moduleReference.get(getModelToken(ModelName[reference]));
}

Assuming that ModelName[reference] refers back to a mongoose model name (i.e. Cat.name or just 'Cat')

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • Oh yes, that's it. But, I don't know why Nestjs says `Nest could not find ImageBoundingBoxModel element (this provider does not exist in the current context)`. I tried with `{strict: true}` in the second arg but still no luck. Do you have any suggestions? or should I like preload something before? – fsevenm Aug 13 '21 at 00:50
  • If `MongooseModule.forFeature([])` called for each module references you're trying to resolve? That would be my first guess – Jay McDoniel Aug 13 '21 at 00:51
  • I'll try that, will back and accept the answer once I get it worked. Thanks – fsevenm Aug 13 '21 at 04:57
  • 1
    Now works, with additional argument `{strict: false}`. It's `this.moduleReference.get(getModelToken(ModelName[reference]), {strict: false});`. – fsevenm Aug 19 '21 at 04:48
  • I always seem to forget to add the `{ strict: false }` when talking about the `moduleRef`'s `get` method. Thanks for adding that in – Jay McDoniel Aug 19 '21 at 05:01