Can multiple MongoDB models be injected into one resolver and used?
I attempted to accomplish this by first adding the import of SectionSchema and SectionsService to the PostsModule:
@Module({
imports: [MongooseModule.forFeature([{name: 'Post', schema: PostSchema}, {name: 'Section', schema: SectionSchema}])],
providers: [PostsResolver, PostsService, SectionsService],
})
export class PostsModule {}
Then I included all the Schema imports in the SectionModule as follows:
@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 {}
Finally, I injected all these models into the constructor of my 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 ...
}
When attempting to run the project using npm run start:dev
, the following error is encountered:
Nest can't resolve dependencies of the SectionsService (SectionModel, PostModel, ?, TutorialModel). Please make sure that the argument ProjectModel at index [2] is available in the PostsModule context.
Is it possible to inject multiple MongoDB models?
ResolverProperty
@ResolveProperty(() => [SectionEntity])
async sections(@Parent() { _id }: PostEntity): Promise<SectionEntity[]> {
const posts: any = await this.postsService.findAll();
return this.sectionsService.findAll(_id, ArticleType.POST);
}