【问题标题】:Nest can't resolve dependencies of the serviceNest 无法解析服务的依赖关系
【发布时间】:2020-04-12 00:17:18
【问题描述】:

是否可以将多个 MongoDB 模型注入到一个解析器中然后使用它们?

我试图这样做: 首先,我将 SectionSchemaSectionsService 导入添加到 PostsModule

@Module({
  imports: [MongooseModule.forFeature([{name: 'Post', schema: PostSchema}, {name: 'Section', schema: SectionSchema}])],
  providers: [PostsResolver, PostsService, SectionsService],
})
export class PostsModule {}

然后我像这样将所有 Schema 导入添加到 SectionModule

@Module({
  imports: [MongooseModule.forFeature([
    {name: 'Section', schema: SectionSchema},
    {name: 'Post', schema: PostSchema},
    {name: 'Project', schema: ProjectSchema},
    {name: 'Tutorial', schema: TutorialSchema},
    ])],
  providers: [SectionsResolver, SectionsService],
})
export class SectionsModule {}

最后,我在 SectionsService

的构造函数中注入了所有这些模型
@Injectable()
export class SectionsService {
  constructor(
    @InjectModel('Section') private readonly sectionModel: Model<SectionEntity>,
    @InjectModel('Post') private readonly postModel: Model<PostEntity>,
    @InjectModel('Project') private readonly projectModel: Model<ProjectEntity>,
    @InjectModel('Tutorial') private readonly tutorialModel: Model<TutorialEntity>) {}
// find, create methods ...
}

当我尝试使用 npm run start:dev 运行我的项目时,我收到了这个错误:

Nest 无法解析 SectionsService 的依赖项(SectionModel、PostModel、?、TutorialModel)。请确保索引 [2] 处的参数 ProjectModel 在 PostsModule 上下文中可用。

是否可以注入多个 MongoDB 模型?

解析器属性

  @ResolveProperty(() => [SectionEntity])
  async sections(@Parent() { _id }: PostEntity): Promise<SectionEntity[]> {
    const posts: any = await this.postsService.findAll();
    return this.sectionsService.findAll(_id, ArticleType.POST);
  }

【问题讨论】:

    标签: mongodb typescript mongoose nestjs


    【解决方案1】:

    您的部分服务很好,您的PostModule 中提供了您的SectionsService,这是错误的来源,因为您的PostModule 没有为ProjectModelSectionService 提供上下文取决于。如果您的PostService 需要您的SectionService 才能正常运行,请考虑从您的SectionsModule 导出SectionsService 并在您的PostModule 中导入SectionsModule

    您需要从SectionsModule 中导出SectionsService,以便在其他模块中使用它。在您的 SectionsModule 中,您应该添加这一行 exports: [SectionsService] 并在您的 PostModule 中添加 imports: [SectionsModule, /*rest of your imports */],以便模块具有所需的上下文。

    通过导出SectionsService,我们明确告诉Nest“该服务将在其原始模块之外使用”。 Nest 非常注重模块化和关注点分离的思想,这意味着很多东西,当以某种方式制作时,理论上可以即插即用。默认情况下,我们在 Nest 中创建的每项服务都仅限于它在 providers 数组中的模块。为了让它在任何其他模块中可用,我们需要将它添加到导出数组中,因此,清除范围并说,只要这个模块被导入,这个服务就可用

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 2022-01-17
      • 2018-11-21
      • 2020-03-12
      • 2020-07-03
      相关资源
      最近更新 更多