Nest无法解析USERRepository的依存关系

时间:2018-10-20 10:34:38

标签: javascript node.js typescript nestjs typeorm

这确实是一个意想不到的问题。

当我在终端上输入“ npm run start”时,出现错误。

[Nest] 40671   - 2018-10-20 17:46:37   [ExceptionHandler] Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context. +22ms
Error: Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context.
    at Injector.lookupComponentInExports (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/@nestjs/core/injector/injector.js:139:19)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:160:7)
    at Function.Module.runMain (module.js:703:11)
    at Object.<anonymous> (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/ts-node/src/_bin.ts:177:12)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
 1: node::Abort() [/usr/local/bin/node]
 2: node::Chdir(v8::FunctionCallbackInfo<v8::Value> const&) [/usr/local/bin/node]
 3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [/usr/local/bin/node]
 4: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) [/usr/local/bin/node]
 5: v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/usr/local/bin/node]
 6: 0x909046042fd
Abort trap: 6

我尽了一切努力,但解决不了。我的代码如下:

下面是[app.module.ts]

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import {TypeOrmModule} from '@nestjs/typeorm';

@Module({
  imports: [TypeOrmModule.forRoot(
{
      "type":"postgres",
      "name":"pm_main",
      "host": "localhost",
      "port": 5432,
      "username": "postgres",
      "password": "test",
      "database": "test",
      "synchronize":true
  }
  ),UserModule],
  controllers: [AppController],
  providers: [AppService]
})
export class AppModule {}

以下是[user.service.ts]

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { USER } from './models/user.model';
import { Repository } from 'typeorm';

@Injectable()
export class UserService {

    constructor(
        @InjectRepository(USER)
        private readonly userRepository: Repository<USER>
    ){}

    async findAllUser(): Promise<USER[]> {
        return await this.userRepository.find();
    }
}

下面是[user.module.ts]

import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { PROJECT } from 'project/models/project.model';
import { TypeOrmModule } from '@nestjs/typeorm';
import { USER } from './models/user.model';

@Module({
  imports: [TypeOrmModule.forFeature([USER])],
  providers: [UserService],
  controllers: [UserController],
  exports: [UserService]
})
export class UserModule {}

我100%遵循了文档的样本,但这似乎不正确。

有关更多信息,package.json中的依赖项如下:

"dependencies": {
    "@nestjs/common": "^5.3.9" 
    "@nestjs/core": "^5.3.10", 
    "@nestjs/typeorm": "^5.2.0",
    "ajv": "^6.5.4",
    "class-validator": "^0.9.1",
    "fastify-formbody": "^2.0.0",
    "jsonwebtoken": "^8.3.0",
    "passport": "^0.4.0",
    "passport-jwt": "^4.0.0",
    "pg": "^7.4.3",
    "reflect-metadata": "^0.1.12",
    "rxjs": "^6.0.0",
    "typeorm": "^0.2.7",
    "typescript": "^2.6.2"

还以[USER.model.ts]身份显示为USER

import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToMany, JoinTable } from "typeorm";
import { IsNotEmpty, IsDate, IsEmail, IsArray, IsEnum, IsJSON } from 'class-validator'
import { user_Gender, user_Status } from "./user.enum";
import { PROJECT } from 'project/models/project.model';

@Entity()
export class USER {
    @PrimaryGeneratedColumn('uuid')
    id:string;

    @Column({unique:true})
    @IsNotEmpty()
    username:string;

    @Column()
    password:string;

    @Column()
    @IsEnum({user_Gender})
    gender:string;

    @Column("jsonb")
    @IsJSON()
    realname?:{
        firstName:string;
        lastName:string;
        middleName:string;
    };

    @Column()
    @IsDate()
    birthday?:Date;

    @CreateDateColumn()
    createAt:Date;

    @UpdateDateColumn()
    updateAt:Date;

    @Column()
    @IsArray()
    industry?:string[];

    @Column()
    @IsEmail()
    email?:string;

    @Column()
    @IsArray()
    org?:string[];

    @Column()
    current_org?:string;

    @Column("jsonb")
    @IsJSON()
    user_location?:{
        country:string;
        province_or_state:string;
        city:string;
        district:string;
        address:string;
    };

    @Column("jsonb")
    @IsJSON()
    mobilephone?:{code:string,number:string};

    @Column("text")
    avater:string;

    @Column()
    @IsArray()
    receive_account?:[{
        name:string,
        number:string,
        bank:string,
        swiftCode?:string,
        address?:string}]

    @Column()
    @IsDate()
    last_loginAt?:Date;

    @Column()
    @IsEnum(user_Status)
    status:string;

    @Column()
    projectsId:[];

    @ManyToMany(type => PROJECT, project => project.members)
    @JoinTable()
    projects:PROJECT[];

}

3 个答案:

答案 0 :(得分:5)

问题

问题是您要在根导入中为数据库分配名称:

imports: [TypeOrmModule.forRoot({
      "type":"postgres",
      "name":"pm_main",
      ^^^^^^^^^^^^^^^^^
      "host": "localhost",
      "port": 5432,
      "username": "postgres",
      "password": "test",
      "database": "test",
      "synchronize":true
  }

但是您在forFeature导入中不要使用相同的名称:

imports: [TypeOrmModule.forFeature([USER])],


解决方案

a)因此,可以将名称添加到forFeature导入中:

TypeOrmModule.forFeature([USER], 'pm_main')

b)或从"name":"pm_main",导入中删除forRoot。如果只有一个数据库,则只能依靠隐式默认名称。

答案 1 :(得分:0)

希望获得帮助。

import { UserEntity } from './user.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
const module = await Test.createTestingModule({
    controllers: [UsersController],
    providers: [UsersService],
    imports: [TypeOrmModule.forRoot(), TypeOrmModule.forFeature([UserEntity])], // <== This line
}).compile();

答案 2 :(得分:0)

当使用多个数据库时,Kim的解决方案不能完全解决问题。

在解决此问题时最终解决。 https://github.com/nestjs/typeorm/issues/105

也就是说,@ InjectRepositry(Model,connectionName)时也需要指定连接名称