【问题标题】:How to inject model in root app module in nest js app如何在嵌套js应用程序的根应用程序模块中注入模型
【发布时间】:2020-08-02 23:23:42
【问题描述】:

您好,我的 Nest 应用程序出现错误,这是错误的屏幕截图:

这里是app模块的代码:

@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 {}

这是模型的代码:

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

这是UsersServices的代码:

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

【问题讨论】:

  • 错误提示nestjs 无法解析您的UsersService 的依赖关系。贴出服务代码
  • 已添加代码。问题已更新

标签: typescript jwt nestjs


【解决方案1】:

尝试添加 MongooseModule.forFeature([{ name: 'credentials', schema: credentials }]) 到 AppModule 的导入部分。

架构方面的用户服务和身份验证应该封装在它们自己的模块中。

【讨论】:

    【解决方案2】:

    除了 kaznovac 所说的之外,您还需要从 imports 数组中删除您的 AppModule。此外,看起来您已经拥有UsersModule,您应该从AppModule 的providers 数组中删除UsersModule 提供的所有提供程序。否则,Nest 将尝试再次实例化这些提供程序。

    【讨论】:

    • 我有一个用于 CRUD API 的 CrudModule。一个是根模块,它是 AppModule,我在其中进行了 mongo db 连接。按照你的方法,我得到了错误,错误:Nest can't resolve dependencies CrudService (?) 的。请确保索引 [0] 处的参数 studentModel 在 CrudModule 上下文中可用
    • 嗯,您在模块内使用的任何提供程序也需要在同一个模块中导入。这是 NestJS 的基石。因此,您可以将CrudModule 添加到UsersModule 的imports 数组中,或者您可以将CrudModule 设为@Global(),只要确保您知道自己在做什么。
    猜你喜欢
    • 2016-11-29
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 2017-07-18
    • 2012-10-18
    相关资源
    最近更新 更多