代码之家  ›  专栏  ›  技术社区  ›  Krzysztof Kaczyński

有可能将许多MongoDB模型注入解析器吗?

  •  0
  • Krzysztof Kaczyński  · 技术社区  · 6 年前

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

    我试着这样做: 首先我补充说 节模式 和 部门服务 导入到 后模块

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

    然后我将所有模式导入添加到 分段模块 就像这样:

    @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 {}
    

    最后,我把所有这些模型都注入了我的 部门服务

    @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);
      }
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   Jay McDoniel    6 年前

    你的部门服务很好,你有自己的 SectionsService 在你的 PostModule 这就是错误的来源,就像你的 后模块 没有为 ProjectModel 这个 SectionService 看情况而定。如果你的 PostService 需要你的 部门服务 若要正常运行,请考虑导出 部门服务 从你的 SectionsModule 以及导入 节模块 在你的 后模块 .

    你需要导出 部门服务 从 节模块 因此,它可以用于其他模块。在你的 节模块 你应该加上这一行 exports: [SectionsService] 在你的 后模块 你应该 imports: [SectionsModule, /*rest of your imports */] 使模块具有所需的上下文。

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