A step-by-step guide on injecting a model within the root app module of a Nest JS application

Hello, I encountered an error in my Nest app and here is a screenshot of the error:

https://i.stack.imgur.com/zY1io.png

Below is the code snippet for the AppModule:

@Module({
  imports: [AppModule,CrudModule,MongooseModule.forRoot("mongodb://localhost:27017/mydb"),AuthModule,UsersModule,MulterModule.register({
    dest:'./uploads',
  })],
  controllers: [AppController],
  providers: [AppService,AuthService,UsersService,JwtService],
})
export class AppModule {}

Here is the code snippet for the model:

export interface Credentials extends mongoose.Document{
    email:String,
    password:String
}

And finally, here is the UsersServices code snippet:

import { Injectable } from '@nestjs/common';
//import {logindto} from 'src/crud/DTO/login.dto'
import {Credentials, StudentModel} from 'src/crud/crud.model'
import {model, Model} from 'mongoose'
import {InjectModel} from '@nestjs/mongoose'
//export type User = any;

@Injectable()
export class UsersService {
 constructor(@InjectModel('credentials')private readonly credentials:Model<Credentials> ) {}
  //constructor(@InjectModel('student')private readonly credentials:Model<StudentModel> ){}

  async findByEmail(username: string): Promise<any> {
    return await this.credentials.findOne({
        where: {
            email: username,
        }
    });
  }
}

Answer №1

To enhance your codebase, consider incorporating the following line:

MongooseModule.forFeature([{ name: 'credentials', schema: credentials }])
within the imports section of the AppModule.

From an architectural standpoint, it is advisable to segregate User services and Authentication into their respective modules for better organization.

Answer №2

Building on kaznovac's advice, it is important to exclude the AppModule from the list of imported modules in your code. Moreover, since you seem to already have a UsersModule, make sure to remove any duplicate providers that are also provided by the UsersModule from the AppModule's list of providers. If not removed, Nest may attempt to recreate instances of those providers unnecessarily.

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

Required attributes not found for data type in TypeScript

When the following code snippet is executed: @Mutation remove_bought_products(productsToBeRemoved: Array<I.Product>) { const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine); const reducedPro ...

Issue with Angular ngFor: displaying only one name instead of all names in the loop

In my component.ts file, I have retrieved this data from an API call: [ [ { "name": "name one", "desc": "something here", }, { "name": &quo ...

What is the best way to interrupt the current song playing?

I am currently working on developing an audio player using reactjs that has a design similar to this https://i.sstatic.net/Hnw0C.png. The song boxes are rendered within a map function, and when any song box is clicked, it should start playing. However, I a ...

Understanding how to efficiently map through FontAwesome icons using React TypeScript and effectively showcase them on the frontend

I am in the process of developing a versatile component that allows me to input the href, target, and rel attributes, along with specifying the FontAwesome Icon I want to utilize. My goal is to be able to pass multiple icons into this list, which will then ...

type of key extractor is unknown in React Native

How can I specify a type for the renderItem function of a FlatList in React Native? This is my current approach: // Importing the generic type for the FlatList render item function import { ListRenderItem } from "react-native"; // Assigning the ...

Angular: Issue with object instantiation - Unable to assign property

Having trouble populating my array due to instantiation issues. Defined Models: user: User = { firstName: "", lastName: "", address: "" } order: Order = { OrderId: "", User: this.user, TotalPrice: 0, OrderItems: [] } Attempting to populat ...

`mat chip component in Angular Material is malfunctioning`

Whenever I input a string, it does not display properly within the designated textbox. HTML <mat-form-field class="favorite-fruits"> <mat-label>Favorite Fruits</mat-label> <mat-chip-list #chipList aria- ...

The Observer<T> generic type necessitates the specification of 1 type argument

I'm currently trying to grasp the concept of Observables in Angular 4. While watching a tutorial video on it, I attempted to create my first Observable but encountered an error in my IDE: The generic type Observer requires 1 types argument(s) Here ...

The validation of DOM nesting has detected that a <td> element cannot be placed within an <a> element

When working on a React project with Material UI, I encountered an issue while trying to create a table. My goal was to make the entire row clickable, directing users to a page with additional information on the subject. Below is the snippet of code for th ...

How to trigger a component programmatically in Angular 6

Whenever I hover over an <li> tag, I want to trigger a function that will execute a detailed component. findId(id:number){ console.log(id) } While this function is executing, it should send the id to the following component: export class ...

We're sorry, the request was blocked due to a missing Access-Control-Allow-Origin header

Recently, while working on a blog application with the front end in react + typescript and backend in go iris, I encountered an issue when trying to fetch blog content using a get request. The backend was running on localhost:5000 and the node at localhost ...

Error arises when attempting to pass interface props to a component in a React Typescript application

I am currently delving into the world of React js and typescript. As part of my learning process, I have created a demo application that allows users to input their name and age. The app features an ErrorModal that should pop up on the screen whenever inco ...

Intellisense from @reduxjs/toolkit is not showing up in my VS Code editor

My experience with vscode is that intellisense does not recognize @reduxjs/toolkit, even though the code itself is functioning correctly. I have already installed the ES7+ React/Redux/React-Native snippets extension from here. Here are a couple of issues ...

Encountered an error while trying to create a new NestJS project using yarn: Command execution failure - yarn install --

Having trouble installing a new NestJs project using yarn. Operating system : Microsoft Windows [version 10.0.19044.3086] Node version : 18.17.1 npm version : 9.6.7 yarn version : 1.22.19 Nest cli version : 10.1.16 I attempted to install by running : npm ...

There was a problem with the WebSocket handshake: the response header value for 'Sec-WebSocket-Protocol' did not match any of the values sent

I've encountered an issue with my React project that involves streaming live video through a WebSocket. Whenever the camera firmware is updated, I face an error in establishing the WebSocket connection. Here's how I initiate the WebSocket: wsRe ...

Integrating Vimeo videos into Angular applications

I am attempting to stream videos using URLs in my Angular application. Every time I try, I encounter the following error: Access to XMLHttpRequest at 'https://player.vimeo.com/video/548582212?badge=0&amp;autopause=0&amp;player_id=0&amp;ap ...

Modifying the color of the error icon in Quasar's q-input component: a step-by-step guide

https://i.stack.imgur.com/4MN60.png Is it possible to modify the color of the '!' icon? ...

Error message stating 'is not recognized' caused by Angular SharedModule

I have a navbar component that I've organized into a module called 'NavbarModule' so that it can be easily shared. My goal is to use this component in the 'ProductsListComponent'. However, even after properly importing and exportin ...

having difficulty interpreting the information from angular's httpclient json request

After creating an Angular function in typescript to make an http request for JSON data and save it to an object, I noticed that the function requires two clicks of the associated button to work properly. Although the connection and data parsing are success ...

In the process of developing a custom Vue component library with the help of Rollup and VueJS 3

My goal is to develop a custom Vue component library using rollup and Vue.js. The process went smoothly with Vue2, but I encountered issues parsing CSS files with Vue3. To address this, I updated the dependencies in the package.json file. package.json { ...