Software Engineering

How to fix @nestjs/mongoose model dependecy injection error in latest update?

1 Answer
1 answers

How to fix @nestjs/mongoose model dependecy injection error in latest update?

0
After updating to recent version of @nestjs/mongoose, serving nest backend started throwing the dependency error like below:

Error: Nest can't resolve dependencies of the XYZService (?). Please make sure that the argument XYZModel at index [0] is available in the XYZModule context.
Potential solutions:
- If XYZModel is a provider, is it part of the current XYZModule?
- If XYZModel is exported from a separate @Module, is that module imported within XYZModule?
  @Module({
    imports: [ /* the Module containing XYZModel */ ]
  })

There are several issues on nest github repo, but there isn't any offitial suggested solution.

It appears that, this issue happens when we have some sort of version incompatibility, for example, if you downgrade to @nest/mongoose@8.0.1, this issue disappears.

Solution without downgrading:
You have to mention the connection name in addition to model name in the @InjectModel decorator.

Before fix:

constructor(
  @InjectModel("XYZModel")
  protected model: Model<XYZDocument>
 ) {}


After fix:


constructor(
  @InjectModel("XYZModel", "XYZConnection")
  protected model: Model<XYZDocument>
 ) {}


Here is the code in @nestjs/mongoose library (in mongoose.utils.ts file), that appends Model keyword to the collection name, that results in the error:


export function getModelToken(model: string, connectionName?: string) {
  if (connectionName === undefined) {
    return `${model}Model`;
  }
  return `${getConnectionToken(connectionName)}/${model}Model`;
}


Hope it helps.
Wrote answer · 8/2/2022
Karma · 1435

Related Questions

How to forward root domain to www in GoDaddy with full URL?
The average is called .............. in statistical language?
यथाशक्ती, पाऊसपाणी या सामातजक शब्दाांचा करून प्रकार तलहा (२)?
What are ingredients?
Instagram like Indian app?