为什么以及如何在NestJS中添加Model作为依赖项



我正在尝试做这个教程,但它对我不起作用。当我运行代码时,我得到了这个错误:

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

我相信这是我需要更改的代码(?(

@Injectable()
export class TestService {
constructor(
@InjectModel('Student') private readonly studentModel: Model<Student>,
@InjectModel('Animals') private readonly animalModel: Model<Animal>,
) {}

Git Repo

  1. 您已经在imports数组中获得了TestService。不要那样做。provides从不属于imports阵列,只有模块做

  2. 要创建@InjectModel('Student')的提供程序,您需要将MongooseModule.forFeature([{ name: 'Student', schema: StudentSchema })])添加到包含TestService(可能是TestModule(的模块的imports数组中,以便Nest可以创建要注入的动态提供程序。


接收存储库后编辑

您使用的是命名数据库连接,因此需要在@InjectModel()中使用相同的连接。CCD_ 11。就像文件显示一样

最新更新