【发布时间】:2020-04-12 00:17:18
【问题描述】:
是否可以将多个 MongoDB 模型注入到一个解析器中然后使用它们?
我试图这样做: 首先,我将 SectionSchema 和 SectionsService 导入添加到 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