可以向解析器注入许多MongoDB模型吗?

时间:2019-11-24 23:50:04

标签: mongodb typescript mongoose nestjs

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

我试图那样做: 首先,我将 SectionSchema SectionsService 导入添加到 PostsModule

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

然后将所有架构导入添加到 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运行项目时,出现此错误:

  

嵌套不能解析SectionsService的依赖项(SectionModel,PostModel,?,TutorialModel)。请确保在PostsModule上下文中索引[2]处的参数ProjectModel可用。

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

ResolverProperty

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

1 个答案:

答案 0 :(得分:1)

您的版块服务很好,您在SectionsService中提供了PostModule,这是错误的出处,因为您的PostModule没有提供{ ProjectModel所依赖的{1}}。如果您的SectionService需要PostService正常运行,请考虑从SectionService导出SectionsService并将SectionsModule导入SectionsModule中。 / p>

您需要从PostModule导出SectionsService,以便可以在其他模块中使用它。在您的SectionsModule中应添加此行SectionsModule,在您的exports: [SectionsService]中应具有PostModule,以便该模块具有所需的上下文。

通过导出imports: [SectionsModule, /*rest of your imports */],我们明确地告诉Nest“此服务将在其原始模块之外使用”。 Nest非常注重模块化和关注点分离的思想,这意味着从理论上讲,以某种方式制作的很多东西都可以即插即用。默认情况下,我们在Nest中提供的每项服务都只限于提供程序数组中所在模块的作用域。要使其在任何其他模块中可用,我们需要将其添加到导出数组,因此,清除作用域并说,只要导入了此模块,此服务就可用