NestJS中Role模型未注入报错,如何正确访问该模型?
NestJS Guard无法访问注入的Model问题解决
问题代码
constructor(resource, action, @InjectModel(Role.name) public roleModel?: Model<Role>) { this.resource = resource; this.action = action; }
错误信息
Role model is not injected yet
at RolesGuard.canActivate (/home/siva/projects/prac360/appointment-api/src/role/role.guard.ts:28:13)
at GuardsConsumer.tryActivate (/home/siva/projects/prac360/appointment-api/node_modules/@nestjs/core/guards/guards-consumer.js:15:34)
解决方法
注册Guard为模块提供者:Guards需要被添加到模块的
providers数组中,Nest才能处理它的依赖注入。示例:@Module({ providers: [RolesGuard], // 若需全局可用,可添加@Global()装饰器或在根模块导入该模块 }) export class RoleModule {}避免手动实例化Guard:如果使用
@UseGuards(),确保传入的是类(@UseGuards(RolesGuard))而非手动创建的实例(new RolesGuard(...))。手动实例化会跳过Nest的依赖注入流程,导致Model无法注入。确认Role模型的模块配置:
- 确保包含
Role实体的模块已经通过MongooseModule.forFeature([{ name: Role.name, schema: RoleSchema }])导入Mongoose特性模块。 - 确保
RolesGuard所在的模块已经导入了包含Role模型的模块(如RoleModule)。
- 确保包含
移除可选依赖标记:将构造函数中
roleModel的?去掉,强制依赖注入,启动时就能检测到注入问题,避免运行时报错:constructor( resource, action, @InjectModel(Role.name) public roleModel: Model<Role> ) { this.resource = resource; this.action = action; }
内容的提问来源于stack exchange,提问作者Sivakumar
相关产品推荐
相关产品推荐

