Nest is encountering difficulty resolving dependencies for MongoDB

I am having an issue with implementing MongoDB in my Nest.js project. Despite what I believe to be a correct installation, I keep encountering the following error:

Nest can't resolve dependencies of the AuthService (SessionRepository, ?). Please ensure that the argument LogRepository at index [1] is available in the AuthModule context.

Below is a snippet of the relevant code:

// app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from '@auth/auth.module';
import { MongooseModule } from '@nestjs/mongoose';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: `../../.env.${process.env.NODE_ENV}`
    }),
    MongooseModule.forRoot(process.env.MONGO_DB_LOGS),
    AuthModule
  ]
})
export class AppModule {}

Authentication module code:

// auth.module.ts

import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { SequelizeModule } from '@nestjs/sequelize';
import { Session } from '@models/session.model';
import { MongooseModule } from '@nestjs/mongoose';
import { Log, LogSchema } from '@mongo-schemas/log.schema';

@Module({
  providers: [AuthService],
  exports: [AuthService],
  controllers: [AuthController],
  imports: [
    MongooseModule.forFeature([{ name: 'Log', schema: LogSchema }]),
  ]
})
export class AuthModule {}

Mongoose schema used in the project:

// log.schema.ts

import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';

@Schema()
export class Log {

  @Prop()
  message: string;
}

export const LogSchema = SchemaFactory.createForClass(Log);

Code for the authentication service:

import { Log } from '@mongo-schemas/log.schema';
import { Model } from 'mongoose';

@Injectable()
export class AuthService {
  constructor(
    @InjectModel(Session) private readonly sessionRepository: typeof Session,
    @InjectModel(Log) private readonly logsRepository: Model<Log>
  ) {}
...

Thank you for your assistance!

PS. Note that the error mentions LogRepository, whereas it should be LogsRepository.

Answer №1

The issue has been resolved by making a discovery. The challenge stemmed from my utilization of both @nestjs/sequelize and @nestjs/mongoose within the same project. In attempting to inject models from both sequelize and mongoose into the same service, I encountered an error when using the @InjectModel decorator from @nestjs/sequelize.

@InjectModel(Session) private readonly sessionRepository: typeof Session,
@InjectModel(Log) private readonly logsRepository: Model<Log>

To rectify this, I imported both decorators but altered the name:

import { InjectModel } from '@nestjs/sequelize';
import { InjectModel as InjectModelMongo } from '@nestjs/mongoose';

Following this adjustment, all functionality is now operating smoothly:

@InjectModel(Session) private readonly sessionRepository: typeof Session,
@InjectModelMongo(InformationLog.name) private readonly logger: Model<InformationLog>

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

Generate TypeScript types automatically based on an object

I'm working with a code snippet that looks like this: import { ApolloClient } from '@apollo/client'; type F = typeof FeaturesManager.features.warrants export class FeaturesManager { static features = { warrants: Symbol('WARRANTS ...

Arranging Data in Mongodb

Currently, I am working on a PHP application that utilizes Mongodb for data storage. When searching using the given code snippet: $regex='/.*sim.*/i'; $find['Word']=new mongoRegex($regex); $cursor = $collection->find($find); I re ...

Create a collection of unique objects using a specific key for each object in the array

Is it possible for TypeScript to define an array that enforces a unique key constraint for specified objects? Check out this demo showing the constraints. type Magician = { distinctKey: string; lastName: string; }; // How, if at all, can we make lin ...

Purging specific information exclusively from MongoDB's secondary database

Is it feasible to remove data from a Mongo secondary instance individually by executing the delete command directly on the secondary without impacting the primary and other secondary instances? Context: I am in need of purging a substantial collection siz ...

Leveraging Cassandra for user registration

I am currently using Cassandra for a social networking application that I am developing. The features of Cassandra are really appealing to me. I am contemplating whether it is safe to store both the username and password in Cassandra itself, or if it would ...

How can I modify the pristine state of NgModel in Angular 2 using code?

Whenever you update the NgModel field, it will automatically set model.pristine to true. Submitting the form does not change the "pristine" status, which is expected behavior and not a bug. In my situation, I need to display validation errors when the fo ...

The page does not appear to be updating after the onClick event when using the useState hook

Having difficulty re-rendering the page after updating state using the useState hook. Although the state value changes, the page does not refresh. export function changeLanguage(props: Props) { const [languageChange, setLanguageChange] = React.useState( ...

Incorporate ES6 Promise directly into Typescript for enhanced Protractor/WebDriverJS ControlFlow capabilities

Currently, I am incorporating external code in my Protractor tests that yield ES6 Promises. I had the intention of chaining these promises using a ControlFlow, but I encountered a type error during Typescript compilation. Within the test: import {browse ...

What could be causing me to lose my login information on my React application?

I have a reactjs application that utilizes a django backend for handling authentication. Below is a snippet of my Typescript code from the App.tsx file in my react app: import React, {useState, useEffect} from 'react'; import { BrowserRouter as ...

Leverage the positional operator $ within the map function in MongoDB's MapReduce algorithm

I have a collection with records structured like this : {"userid": 1, "contents": [ { "tag": "whatever", "value": 100 }, {"tag": "whatever2", "value": 110 } ] } Currently, I am running a MapReduce operation on this collection with queries such as {"cont ...

Function did not get triggered by Firebase AuthStateListener

Greetings! In my Nativescript Angular application, I am verifying at the beginning of the app whether the user is logged in or not and then calling a function based on that. Here's the code snippet: ngOnInit() { firebase.init({ onAuthStat ...

Connect the keys from one enum to either keys or values in another enum

When working with the code below, it is important that the keys of PropertiesNamesInDataBase align with those in User.Keys. While the values of PropertiesNamesInDataBase are used in the backend, it is crucial for uniformity that the names match in the fron ...

Encountering an issue while upgrading to Angular 10: Unable to interpret "tsconfig.json" as a valid JSON AST Object

I'm currently updating my Angular 9 app to Angular 10 and encountering this error: > Removing "Solution Style" TypeScript configuration file support. × Migration failed: Failed to parse "tsconfig.json" as JSON AST Object. PropertyNameExpected at l ...

Steps for clicking on the center of a leaflet map with protractor

I'm currently facing an issue where I am attempting to click on the center of a map located in the second column of the webpage, which has an offset. However, I am encountering a problem where the cursor always points to the center of the page instead ...

Vue textarea not accepting null values

My current setup includes the following dependencies: - "vue": "3.2.26", - "vee-validate": "4.5.6", - "typescript": "4.5.4" While working on a textarea field in vue3, I encountered an issue Here's a snippet with vee-validate integration import { Fie ...

Unable to retrieve information from a function in Vue.js (using Ionic framework)

When attempting to extract a variable from a method, I encounter the following error message: Property 'commentLikeVisible' does not exist on type '{ toggleCommentLikeVisible: () => void; This is the code I am working with: <template& ...

Steps for activating the HTML select option menu with an external button click

I'm currently in the process of building a React website and I'm faced with the challenge of customizing select options to align with my design in Figma. Check out this image for reference Here's how I've set it up in my code: const C ...

How to use multiple template urls in Angular 6

Currently, I am creating a front-end using Angular 6 and facing the challenge of having components with varying html structures based on the user who is logged in. The number of templates required can range from 2 to over 20, so my preference would be to ...

Encountering issue with uploading identical images in express

I am currently working on a project where I am attempting to upload images using Express. However, I have encountered two issues. Firstly, when I try to upload the same image again, it does not get uploaded. Secondly, after uploading a single image, an a ...

transferring data from service to component

Dealing with the challenge of passing a variable from a service (LibraryService) to a component located one level deeper in the directory structure (ReadingPaneComponent) has been quite troublesome for me. This predicament arose after successfully transfer ...