Search code examples
node.jsmongoosenestjsnestjs-mongoose

How can I get model reference on the fly nestjs mongoose


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.


Solution

  • 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')