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

Terminating the program if the initial query yields a result in Node.js Express.js using mongoDB

I have been searching for a solution to this issue for over 2 hours. I am new to working with Express Node MongoDB, and I know the answer is simple but I just can't get it to work. MongoClient.connect(url, function(err, db) { if (err) { r ...

using all mongoDB collections as input for mapreduce hadoop

I am facing a challenge where I need to pass all collections from my MongoDB database as input to a Hadoop MapReduce job. While there is a method that allows multiple inputs, it only supports up to 2 collection arguments: MultiCollectionSplitBuilder mcsb ...

Fill up mongoose with data on 3 schemas

I have successfully populated 2 schema, but I am facing difficulty in populating the third schema. Here are the schemas: Member Schema var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var Schema = mongoose.Schema ...

Refining a Collection of Possible Options

If I have an array of type Maybe<int>[] and want to extract only the values that are not None, what is the most efficient approach while ensuring TypeScript recognizes the output as int[]? It seems like declaring the result type as int[] is the way ...

Utilizing Lazy Loading Modules within an Angular 2 (v5) App

I'm struggling to implement lazy loading in my Angular 2 (version 5.1.3) project. While following Todd Motto's guide on Lazy Loading Code Splitting, I am hitting a roadblock in getting it to function correctly. My app consists of multiple modul ...

Determine whether something has the potential to be a string in TypeScript

I am looking to create a TypeScript type that can identify whether an element has the potential to be a string. This means the element should have the type "string" or "any", but not "number", "boolean", "number[]", "Person", etc. I have experimented wit ...

Error encountered when deploying ExpressJS API on Heroku, resulting in a 500 Internal Server Error

After successfully building my first MERN app and testing everything in my local development environment, I encountered some issues upon deploying my ExpressJS REST API on Heroku. Most of the GET/POST/PATCH requests sent to the backend are working fine aft ...

Creating definitions for generic static members within a third-party module

There is a 3rd party module with the following structure: export class Container{ static async action() { return {...} } constructor(params = {}) { // ... } async doSomething(params = {}) { // ... } } I am looking to de ...

Displaying all keys within a document using MongoDB PyMongo

I'm wondering how to extract all the keys from a document in PyMongo without displaying their values. Let's say we have a document structured like this: { "_id" : ObjectID("...") "name": ABCD, "info": { "description" : "XYZ", ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

Break apart the string and transform each element in the array into a number or string using a more specific type inference

I am currently working on a function that has the ability to split a string using a specified separator and then convert the values in the resulting array to either strings or numbers based on the value of the convertTo property. Even when I call this fun ...

Can you tell me the data type of a Babel plugin parameter specified in TypeScript?

Struggling to find ample examples or documentation on writing a Babel plugin in TypeScript. Currently, I am working on a visitor plugin with the following signature: export default function myPlugin({ types: t }: typeof babel): PluginObj { In order to obt ...

A guide to handling deep updates with subdocuments in Mongodb/Mongoose

In this scenario, I am looking to utilize mongoose. Consider a Schema structured like the following: const userSchema = new Schema({ name: { first: { type: String, required: true }, last: { type: String, required: true }, }, email: { type: S ...

Show information retrieved from one API request within another API request

Currently, I am in the process of retrieving data from the Youtube API by utilizing 2 separate requests. One request is used to fetch a list of videos, while the other request provides details for each individual video. The initial request successfully di ...

Building a Meteor query in MongoDB using $in operator while handling duplicate values

I have a collection of songs that I want to present to a user. Each song is associated with a specific id. The issue I am encountering is that some songs should be displayed multiple times. Currently, I am using the $in operator in my MongoDB query, but it ...

Issue with TypeScript when calling the jQuery getJSON() method

Currently, I am working with TypeScript version 1.7.5 and the latest jQuery type definition available. However, when I attempt to make a call to $.getJSON(), it results in an error message stating "error TS2346: Supplied parameters do not match any signatu ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

Implementing Adsterra in your next.js or react.js project: A step-by-step guide

Currently, I am working on integrating the Adsterra Banner 300x50 into a ts/js reactjs + nextjs project. The provided script code from Adsterra is as follows: <script type="text/javascript"> atOptions = { 'key' : 'XXXXXX&a ...

Developing a Next.js application using Typescript can become problematic when attempting to build an asynchronous homepage that fetches query string values

Having recently started delving into the world of React, Next.js, and Typescript, I must apologize in advance if my terminology is not entirely accurate... My current learning project involves creating an app to track when songs are performed. Within the ...

Struggling to enter the command `zip` and accurately anticipating when inference fails in overloaded functions involving generics

There are times when I encounter this issue without understanding why the inference fails. Specifically, zip behaves correctly when directly used, but not when used within pipe, leaving me puzzled. declare const zip: { <A, B>(input: readonly [re ...