The issue of NestJS dependency injection not working within the MongooseModule.forFeatureAsync function call has been encountered

I'm having an issue setting up a pre-save hook on my User model. Here's the code snippet from my users.module.ts:

@Module({
  controllers: [
    UsersController,
  ],
  exports: [
    UsersService,
  ],
  providers: [
    UsersService,
  ],
  imports: [
    forwardRef(() => AuthModule),
    MongooseModule.forFeatureAsync([
      {
        name: User.name,
        useFactory: (usersService: UsersService) => {
          const schema = UserSchema;

          schema.pre('save', async function(next) {
            // ... more code

            next();
          });

          return schema;
        },
        inject: [UsersService],
      }
    ]),
  ]
})
export class UsersModule {}

An error message is showing up, saying:

Nest can't resolve dependencies of the UserModel (DatabaseConnection, ?). Please make sure that the argument UsersService at index [1] is available in the MongooseModule context.

Potential solutions:

  • Is MongooseModule a valid NestJS module?
  • If UsersService is a provider, is it part of the current MongooseModule?
  • If UsersService is exported from a separate @Module, is that module imported within MongooseModule? @Module({ imports: [ /* the Module containing UsersService */ ] })

Error: Nest can't resolve dependencies of the UserModel (DatabaseConnection, ?). Please make sure that the argument UsersService at index [1] is available in the MongooseModule context.

The users service, with some parts omitted, looks like this:

@Injectable()
export class UsersService {

  constructor(
    @InjectModel(User.name)
    private readonly userModel: Model<User>,
  ) {}

}

When I replace forFeatureAsync with forFeature, everything works fine. Similarly, if I remove inject: [UsersService] and the parameter from useFactory, it also works as expected.

Any ideas on what might be causing this issue?

Answer №1

Attempting to create a circular relationship between the UserService and the UserModel is bound to fail. Perhaps consider extracting the functionality causing the dependency into its own separate module and service, then utilize that within the context of forFeatureAsync. Just make sure to properly import the new module in this case.

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

Why won't my boolean value in the Angular service reflect in the HTML code?

For my project, I am utilizing a stepper and I need to display or hide a div based on the selected product. However, I am encountering an issue where the HTML isn't updating when I try to call the done() function. .service public beneficiary = true; ...

What is the best way to incorporate Ekko Lightbox into an Angular 7 Project?

I'm facing an issue while implementing Ekko lightbox in my angular project. Specifically, I want to use it in a certain component but I am unsure about how to import the necessary files into that component. After installing Ekko via NPM, I found all ...

Switching Facebook accounts on Firebase

I'm currently working on an Angular2 App that utilizes Firebase as its User system, with authentication providers including Email + Password, Facebook, and Google. One issue I have encountered is that when logging in with Facebook, I am unable to swi ...

Can anyone provide guidance on setting up a TypeScript service worker in Vue 3 using the vite-plugin-pwa extension?

I am looking to develop a single-page application that can be accessed offline. To achieve this, I have decided to implement a PWA Service Worker in my Vue webapp using TypeScript and Workbox. I found useful examples and guidance on how to do this at . Ho ...

A peculiar TypeError occurred when testing a React component with Enzyme, preventing the addition of a property as the object is not extensible in the Object

Encountered a peculiar issue during testing where I am trying to merge two objects to use as the style of a component, replicating the component's logic with the code provided below. var styles = { "height": 20 } var expectedStyles = (Object as any). ...

Angular error: Unable to access the 'toLowerCase' property of an undefined value

I've been working on creating my own custom filter pipe by following the instructions in this video tutorial, but I encountered an error message stating, "Angular, TypeError: Cannot read property 'toLowerCase' of undefined". I have already i ...

Could not load ngx-restangular due to an error: (SystemJS) Module not yet loaded while trying to load "@angular/core"

Recently, I made the switch from using the AngularJS 'restangular' library to the Angular 'ngx-restangular' library during an upgrade from AngularJS to Angular. However, after the transition, I encountered an unexpected error along wit ...

Angular 12's BehaviorSubject should have been empty object array, but it unexpectedly returns undefined

Exploring different scenarios with a livesearch functionality: No user input (observable = undefined) No results found (observable = empty array) Results found (observable = non-empty array) The issue lies in how my behavior subject interprets an empty a ...

Tips for deleting on a numeric cell within ag-grid?

While exploring the functionality of AG-Grid with the example provided at this link [, I am currently experimenting with the numeric editor feature. I found this example on the official AG-Grid website [https://www.ag-grid.com/javascript-grid-cell-editor/ ...

Errors from NestJS microservice class validator are visible in the docker container but do not appear in the API response

Seeking assistance with displaying validation errors in my NestJS project using class validator. This is my first time working with microservices and NestJS, as it's for a school project. Errors from my 'user' microservice container are not ...

nodemon failing to automatically refresh files in typescript projects

I am currently developing an app using NodeJs, express, typescript, and nodemon. However, I am encountering an issue where the page does not refresh when I make changes to the ts files. Is there a way for me to automatically compile the ts files to js an ...

Tips for retrieving items from <ng-template>:

When the loader is set to false, I am trying to access an element by ID that is located inside the <ng-template>. In the subscribe function, after the loader changes to false and my content is rendered, I attempt to access the 'gif-html' el ...

Tips for maintaining license comments in TypeScript 2.5

When creating JavaScript libraries using TypeScript v2.5 and tsc, it is important to include license comments in the built files. However, the removeComments configuration in the tsconfig.json file can remove certain comments, including license comments. ...

A function that takes in a type identifier and a portion of a type, and then outputs the full type

I'm currently facing a challenge with TypeScript generics. I have several types (referred to as Animals) that each have a unique attribute, "type." Additionally, I have a function called createAnimal which takes the type of animal and a partial object ...

The class constructor in the TSdx package must be invoked with the 'new' keyword

I recently developed a npm package using TSdx to create a small Jest reporter. However, when I try to use this package in another project, an error occurs. Uncaught TypeError: Class constructor BaseReporter cannot be invoked without 'new' at ...

Issue: Import statement cannot be used outside a module in Appium

Encountering the following error while working on a colleague's laptop, so it appears that there is no issue with the code itself. It could be related to my local packages but I am not entirely certain. node version: v18.20.1 npm version : 10.5.0 impo ...

Changing the mouse cursor dynamically with Angular programming

What is the recommended approach for changing the mouse cursor programmatically in Angular? For instance: HTML: <div [style.cursor]="cursorStyle">Content goes here</div> or <div [ngStyle]="{ 'cursor': cursorStyle ...

You can easily search and select multiple items from a list using checkboxes with Angular and TypeScript's mat elements

I am in need of a specific feature: An input box for text entry along with a multi-select option using checkboxes all in one place. Unfortunately, I have been unable to find any references or resources for implementing these options using the Angular Mat ...

Best practices for transitioning a project from TypeScript 3 to TypeScript 4?

I am looking to upgrade my large monorepo, which was built using lerna, React, and TypeScript 3.7 around 2-3 years ago. My goal is to update it to TypeScript 4.8. Are there any tools available that can help me analyze and identify potential breaking chan ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...