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
Answer link
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.