NestJS依赖注入报错:无法解析ClientsService的依赖
NestJS依赖注入报错解决:ClientModel无法解析
核心问题
报错的根本原因是模型注册名称与注入名称不匹配:
- 在
ClientsService的构造函数中,你用@InjectModel('Client')请求注入名为Client的模型 - 但在
ClientsModule的MongooseModule.forFeature里,注册的模型名称是'Clients'(复数形式)
Nest无法在模块上下文找到对应名称的模型,因此抛出依赖解析失败的错误。
修复方案(二选一即可)
方案1:修改服务中的注入名称,与模块注册一致
修改client.service.ts的构造函数:
constructor(@InjectModel('Clients') private readonly clientModel: Model<Client>) { }
方案2:修改模块中的注册名称,与服务注入一致
修改client.module.ts的MongooseModule.forFeature配置:
MongooseModule.forFeature([{name: 'Client', schema: ClientSchema}])
额外代码优化提示
你的getClient方法参数类型存在错误:clientID应该是字符串(MongoDB文档ID的常规类型),而非Promise<Client>,修正后代码:
async getClient(clientID: string): Promise<Client> { const client = await this.clientModel.findById(clientID).exec(); return client; }
内容的提问来源于stack exchange,提问作者Graham Morby
相关产品推荐
相关产品推荐

