NodeJS NestJS在尝试实现JWT时导入模块时出错

eyh26e7m  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(236)

我正在学习Nest,我想和Mongoose沿着实现JWT。我在nestjs网站上遵循指南,但我一直得到错误:

Nest can't resolve dependencies of the UsersService (?). Please make sure that the argument User at index [0] is available in the UsersModule context.

这是我的代码。
app.module.ts

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: path.resolve(__dirname, '../.env'),
    }),
    MongooseModule.forRoot(process.env.MONGODB_URI),
    AuthModule,
    UsersModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(JwtMiddleware).forRoutes('*');
  }
}

auth.module.ts

@Module({
  imports: [
    UsersModule,
    JwtModule.register({
      global: true,
      secret: process.env.JWT_SECRET,
      signOptions: { expiresIn: '30d' },
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService],
  exports: [AuthService],
})
export class AuthModule {}

users.module.ts

@Module({
  imports: [
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
  ],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}

更新
user.service.ts

@Injectable()
export class UsersService {
  constructor(
    @Inject(User.name)
    private userModel: Model<IUser>,
  ) {}

  async findOne(email: string): Promise<IUser | undefined> {
    const user = this.userModel.findOne({ email: email.toLowerCase() });

    return user;
  }
}
r1wp621o

r1wp621o1#

如文档所示,将@Inject(User.name)更改为@InjectModel(User.name)

相关问题