最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NestJSTypeORM: Cannot set property metadata of #<Repository> which has only a getter - Stack Overflow

programmeradmin2浏览0评论

I try to run my nestjstutorial app, the below error is showing. My backend is connected to a PostgreSQL db.

TypeError: Cannot set property metadata of # which has only a getter at EntityManager.getCustomRepository (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\src\entity-manager\EntityManager.ts:1404:59) at DataSource.getCustomRepository (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\src\data-source\DataSource.ts:465:29) at InstanceWrapper.useFactory [as metatype] (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\typeorm\dist\typeorm.providers.js:13:35) at Injector.instantiateClass (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:333:55) at callback (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:48:41) at processTicksAndRejections (node:internal/process/task_queues:96:5) at Injector.resolveConstructorParams (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:122:24) at Injector.loadInstance (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:52:9) at Injector.loadProvider (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:74:9) at Injector.lookupComponentInImports (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:265:17)

My code looks like this:

app.module

    import { Module } from '@nestjs/mon';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { UserController } from './user/user.controller';
    import { UserModule } from './user/user.module';
    import { UserService } from './user/user.services';
    import { QuizModule } from './modules/quiz/quiz.module';
    //import { QuizController } from './modules/quiz/quiz.controller';
    //import { QuizService } from './modules/quiz/quiz.services';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { typeOrmConfig } from './config/typeorm.config';
    //import { QuizRepository } from './modules/quiz/quiz.repository';
    
    @Module({
      imports: [UserModule, QuizModule, TypeOrmModule.forRoot(typeOrmConfig)],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}

quiz.controller

    import {
      Body,
      Controller,
      Get,
      HttpCode,
      Post,
      UsePipes,
      ValidationPipe,
    } from '@nestjs/mon';
    import { QuizService } from './quiz.services';
    import { CreateQuizDto } from '../dto/CreateQuiz.dto';
    
    @Controller('quiz')
    export class QuizController {
      constructor(private readonly quizService: QuizService) {}
    
      @Get('/')
      getAllQuiz() {
        return this.quizService.getAllQuiz();
      }
    
      @Post('/create')
      @HttpCode(200)
      @UsePipes(ValidationPipe)
      async createQuiz(@Body() quizData: CreateQuizDto) {
        return await this.quizService.createNewQuiz(quizData);
      }
    }

quiz.services

    import { Injectable } from '@nestjs/mon';
    import { InjectRepository } from '@nestjs/typeorm';
    import { QuizRepository } from './quiz.repository';
    import { CreateQuizDto } from '../dto/CreateQuiz.dto';
    
    @Injectable()
    export class QuizService {
      constructor(
        @InjectRepository(QuizRepository) private quizRepository: QuizRepository,
      ) {}
    
      getAllQuiz() {
        return [1, 2, 'from service', 3];
      }
      async createNewQuiz(quiz: CreateQuizDto) {
        return await this.quizRepository.save(quiz);
      }
    }

quiz.module

    import { Module } from '@nestjs/mon';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { QuizController } from './quiz.controller';
    import { QuizService } from './quiz.services';
    import { QuizRepository } from './quiz.repository';
    
    @Module({
      controllers: [QuizController],
      imports: [TypeOrmModule.forFeature([QuizRepository])],
      providers: [QuizService],
    })
    export class QuizModule {}

quiz.repository

    import { EntityRepository, Repository } from 'typeorm';
    import { Quiz } from './quiz.entity';
    
    @EntityRepository(Quiz)
    export class QuizRepository extends Repository<Quiz> {
      //<Quiz> means Quiz module
    }

typeorm.config

import { TypeOrmModuleOptions } from '@nestjs/typeorm';

    export const typeOrmConfig: TypeOrmModuleOptions = {
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: '123456',
      database: 'quiz',
      entities: [__dirname + '/../**/*.entity{.ts,.js}'],
      synchronize: true,
    };

dto

import { isNotEmpty, IsNotEmpty, Length } from 'class-validator';

export class CreateQuizDto {
  @IsNotEmpty({ message: 'Title mandatory' })
  @Length(3, 255)
  title: string;

  @IsNotEmpty()
  @Length(3)
  description: string;
}

entity

import { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity('quizes')
export class Quiz extends BaseEntity {
  @PrimaryGeneratedColumn({
    ment: 'The quiz unique identifier',
  })
  id: number;

  @Column({
    type: 'varchar',
  })
  title: string;

  @Column({
    type: 'text',
  })
  description: string;

  @Column({
    type: 'varchar',
  })
  usernmae: string;

  @Column({
    type: 'date',
  })
  createddate: Date;

  @Column({
    type: 'boolean',
    default: 1,
  })
  isActive: boolean;
}

Somebody know how can I fix this?

I try to run my nestjstutorial app, the below error is showing. My backend is connected to a PostgreSQL db.

TypeError: Cannot set property metadata of # which has only a getter at EntityManager.getCustomRepository (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\src\entity-manager\EntityManager.ts:1404:59) at DataSource.getCustomRepository (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\src\data-source\DataSource.ts:465:29) at InstanceWrapper.useFactory [as metatype] (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\typeorm\dist\typeorm.providers.js:13:35) at Injector.instantiateClass (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:333:55) at callback (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:48:41) at processTicksAndRejections (node:internal/process/task_queues:96:5) at Injector.resolveConstructorParams (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:122:24) at Injector.loadInstance (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:52:9) at Injector.loadProvider (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:74:9) at Injector.lookupComponentInImports (D:\Ganesh\MyDrive\nestjs\nestjs_tutorial\nestjsturorial\node_modules@nestjs\core\injector\injector.js:265:17)

My code looks like this:

app.module

    import { Module } from '@nestjs/mon';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { UserController } from './user/user.controller';
    import { UserModule } from './user/user.module';
    import { UserService } from './user/user.services';
    import { QuizModule } from './modules/quiz/quiz.module';
    //import { QuizController } from './modules/quiz/quiz.controller';
    //import { QuizService } from './modules/quiz/quiz.services';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { typeOrmConfig } from './config/typeorm.config';
    //import { QuizRepository } from './modules/quiz/quiz.repository';
    
    @Module({
      imports: [UserModule, QuizModule, TypeOrmModule.forRoot(typeOrmConfig)],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}

quiz.controller

    import {
      Body,
      Controller,
      Get,
      HttpCode,
      Post,
      UsePipes,
      ValidationPipe,
    } from '@nestjs/mon';
    import { QuizService } from './quiz.services';
    import { CreateQuizDto } from '../dto/CreateQuiz.dto';
    
    @Controller('quiz')
    export class QuizController {
      constructor(private readonly quizService: QuizService) {}
    
      @Get('/')
      getAllQuiz() {
        return this.quizService.getAllQuiz();
      }
    
      @Post('/create')
      @HttpCode(200)
      @UsePipes(ValidationPipe)
      async createQuiz(@Body() quizData: CreateQuizDto) {
        return await this.quizService.createNewQuiz(quizData);
      }
    }

quiz.services

    import { Injectable } from '@nestjs/mon';
    import { InjectRepository } from '@nestjs/typeorm';
    import { QuizRepository } from './quiz.repository';
    import { CreateQuizDto } from '../dto/CreateQuiz.dto';
    
    @Injectable()
    export class QuizService {
      constructor(
        @InjectRepository(QuizRepository) private quizRepository: QuizRepository,
      ) {}
    
      getAllQuiz() {
        return [1, 2, 'from service', 3];
      }
      async createNewQuiz(quiz: CreateQuizDto) {
        return await this.quizRepository.save(quiz);
      }
    }

quiz.module

    import { Module } from '@nestjs/mon';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { QuizController } from './quiz.controller';
    import { QuizService } from './quiz.services';
    import { QuizRepository } from './quiz.repository';
    
    @Module({
      controllers: [QuizController],
      imports: [TypeOrmModule.forFeature([QuizRepository])],
      providers: [QuizService],
    })
    export class QuizModule {}

quiz.repository

    import { EntityRepository, Repository } from 'typeorm';
    import { Quiz } from './quiz.entity';
    
    @EntityRepository(Quiz)
    export class QuizRepository extends Repository<Quiz> {
      //<Quiz> means Quiz module
    }

typeorm.config

import { TypeOrmModuleOptions } from '@nestjs/typeorm';

    export const typeOrmConfig: TypeOrmModuleOptions = {
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: '123456',
      database: 'quiz',
      entities: [__dirname + '/../**/*.entity{.ts,.js}'],
      synchronize: true,
    };

dto

import { isNotEmpty, IsNotEmpty, Length } from 'class-validator';

export class CreateQuizDto {
  @IsNotEmpty({ message: 'Title mandatory' })
  @Length(3, 255)
  title: string;

  @IsNotEmpty()
  @Length(3)
  description: string;
}

entity

import { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity('quizes')
export class Quiz extends BaseEntity {
  @PrimaryGeneratedColumn({
    ment: 'The quiz unique identifier',
  })
  id: number;

  @Column({
    type: 'varchar',
  })
  title: string;

  @Column({
    type: 'text',
  })
  description: string;

  @Column({
    type: 'varchar',
  })
  usernmae: string;

  @Column({
    type: 'date',
  })
  createddate: Date;

  @Column({
    type: 'boolean',
    default: 1,
  })
  isActive: boolean;
}

Somebody know how can I fix this?

Share Improve this question edited Apr 17, 2022 at 5:26 ganesh asked Apr 16, 2022 at 5:43 ganeshganesh 1433 silver badges12 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 11

I had the same problem and the solution was the following: you have to make sure that the version of nestjs/typeorm and typeorm are patible in my case I had version of nestjs/typeorm 8.0.3 and typeorm 0.3.6 , these versions are not patible , version 8.0.3 of nest is patible with version 0.2.34. When I changed my typeorm version to 0.2.34 it piled successfully.

package.json version image

Which version of @nestjs/typeorm and typeorm are you using? If you are using typeorm > 0.3 this is a known issue and using the required typeorm will solve the issue.

I also had the same problem, with @nestjs/typeorm v8.1.4 and TypeORM 0.3.12

However, since v8.1.0, @nestjs/typeorm is patible with TypeORM 0.3.

Therefore, it should be working without downgrading. Still, doing custom repositories with TypeORM 0.3 is quite different.

I was able to make the necessary changes by following this article.

since you are using CustomRepository you should remove the InjectRepository decorator and simply let NestJS inject it.

quiz.service

constructor(
    private quizRepository: QuizRepository,
) {}

you haven't posted your typeorm.config file so make sure to declare Quiz entity so TypeORM will know where to look for it.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论