Nest is having trouble resolving dependencies for this service

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);
  }

Answer №1

Your section service is functioning well, but there seems to be an error in your PostModule where the SectionsService is provided without a context for the ProjectModel that it depends on. If your PostService relies on the SectionService, consider exporting the SectionsService from the SectionsModule and importing it into the PostModule.

To make the SectionsService usable in other modules, you need to export it from the SectionsModule. In the SectionsModule, add exports: [SectionsService] and in the PostModule, include

imports: [SectionsModule, /*rest of your imports */]
to establish the necessary context.

By exporting the SectionsService, we are explicitly indicating to Nest that this service will be utilized outside of its original module. Nest prioritizes modularization and separation of concerns, allowing for plug-and-play functionality in theory. By default, services in Nest are limited to the module they are specified in the providers array. To extend access to other modules, we must add them to the exports array, thereby expanding the scope and making the service available as long as the module is imported.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preserving the Mobile Stepper's current state when the next button is clicked

To maintain the progress state of the Mobile Stepper, even when a user logs out and logs back in, it is crucial to save the current position. The goal is for the user to resume from where they left off, such as at 2% completion instead of starting over at ...

The concept of a generic type serving as a characteristic of an incoming argument

What is the best way to assign a type property of an argument to a generic in TypeScript? Here's the code snippet: const foo = <T = someObject.bar>(someObject: {[string]: any}): T => { return someObject.bar } How can we set the type of ...

Utilize functional JS code within a TypeScript environment

Attempting to integrate this code into a TypeScript project, it is a modified version of the react-custom-scrollbars. I am struggling with TypeScript in regards to declaring types for style and props. In this particular case, I prefer to bypass type check ...

Error message: NestJS encountered a problem with Neovim due to an import prefix missing and the inability to load a local module

This issue can be frustrating as it doesn't affect the functionality of the program. However, upon opening a new or existing NestJS application, all imports are highlighted as errors. For instance, in the main.ts file, there are two imports: import { ...

Using an array of objects as a data source for the Material Angular table

My user data is causing some issues and looks like this... [{"firstName":"Pinkie","lastName":"Connelly","username":"Darlene.Marvin","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="19506a767b7c75464b7c77777c6b5971766d74 ...

What is the correct way to implement fetch in a React/Redux/TS application?

Currently, I am developing an application using React, Redux, and TypeScript. I have encountered an issue with Promises and TypeScript. Can you assist me in type-defining functions/Promises? An API call returns a list of post IDs like [1, 2, ..., 1000]. I ...

Testing server sent events with Angular solely using Karma-Jasmine

I am currently developing a web application using Angular for the frontend and Python for the backend. My implementation involves utilizing server-sent events (SSE) to stream data from the server to the user interface. While everything is functioning prope ...

Exploring Blob functionality in TypeScript?

I defined a global Blob object: declare global { interface Blob { prototype: Blob; new (name: string, url: string): Blob; } } It is functioning correctly in this code snippet: export const blobToFile = (blob: Blob) => { let file: File | n ...

Retrieving information using React Query in TypeScript

When working with React Query and TypeScript, I encountered an issue with the getRecommendations hook. I wanted to only send the latest recommendations (I may create another hook for watchlist items in the future). The error I received was related to the q ...

What is the best way to set the typing of a parent class to the child constructor?

I am seeking a method to inherit the parameter types of a parent's constructor into the child's constructor. For example: class B extends A { constructor (input) { super(input); } } I attempted the following: class B extends ...

Node corrupting images during upload

I've been facing an issue with corrupted images when uploading them via Next.js API routes using Formidable. When submitting a form from my React component, I'm utilizing the following functions: const fileUpload = async (file: File) => ...

Angular's queryParams do not appear to properly connect with the query parameters

My code seems to have a mistake somewhere, but I can't figure it out. In my [queryParams] = "{allowEdit: server.id == 3 ? 1 : 0}", the params object is empty when I subscribe to it in the edit-server component. Why is it empty and how do I a ...

In order to emphasize the chosen list item following a component refresh

SCENARIO: Let's consider a scenario where I have a component named list, responsible for displaying a list of all customers. Within this list, certain conditions are set up as follows: 1) Initially, the 1st list-item (e.g. Customer 1) is selected by ...

Managing arrays in local storage with Angular 2+

I seem to be missing a crucial element in my endeavor to save and retrieve an array in local storage within my Angular 4 application. The array is fetched from the server and stored in a variable named 'aToDo' with type 'any', like so: ...

What is the best way to ensure the user document is saved when a new post is being created

Having resolved previous issues, my focus now is on populating the user document with posts. Here is the current structure of the user document: { "posts": [], "_id": "5e75cf827ef14514f69c6714", "username": "di ...

The video in the TypeScript code within the Owl Carousel is not displaying properly - only the sound is playing. The video screen remains stationary

I recently updated my query. I am facing an issue while trying to play a video in Owl Carousal with a button click. The video plays sporadically, and most of the time it doesn't work properly. When playing without the carousel, a single video works fi ...

Utilizing TypeScript to enhance method proxying

I'm currently in the process of converting my JavaScript project to TypeScript, but I've hit a roadblock with an unresolved TypeScript error (TS2339). Within my code base, I have a class defined like this: export const devtoolsBackgroundScriptCl ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

The ReferenceError occurs exclusively during the execution of tests

I keep encountering a dull stacktrace after executing my test. I've experimented with solutions like using fakeTimers, require('iconv-lite')..., etc, based on these queries: Encoding not recognized in jest.js ReferenceError: You are trying ...

Load Angular component on demand with necessary dependencies

Searching for an elegant solution (without resorting to private APIs) to create a widget-style dashboard. The goal is to dynamically load components based on user role. Is there a way to import a component and its dependencies included in the component&ap ...