Search code examples
javascriptnestjs

Nest js - error No overload matches this call


js and currently learning on making a crud operations.

i got an error on users.service saying

No overload matches this call. Overload 1 of 3, '(this: (new () => User) & typeof BaseEntity, entityLikeArray: DeepPartial[]): User[]', gave the following error.

and

Property 'save' does not exist on type 'User[]'.

on await user.save();

this is my users.service

import { CreateUserDto } from './dto/create-user.dto';
import { User } from './user.entity';

@Injectable()

    export class UsersService {
    
        async create(createUserDto: CreateUserDto) {
            const user = User.create(createUserDto);
            await user.save();
        
            delete user.password;
            return user;
        }
        
    }

create-user.dto.ts

import { IsEmail, IsNotEmpty } from "class-validator";
    export class CreateUserDto{
        @IsEmail()
        email: string;
    
        @IsNotEmpty()
        password:string;
    }

users.controller:

export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
  }
}

users.entity:

import { BaseEntity, BeforeInsert, Column, CreateDateColumn, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
import * as bcrypt from 'bcryptjs';

export class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    email: string;

    @Column()
    password: string;

    @Column()
    @CreateDateColumn()
    createdAt: Date;

    @Column()
    @UpdateDateColumn()
    updatedAt: Date;

    @BeforeInsert()
    async hashPassword() {
        this.password = await bcrypt.hash(this.password, 8);
    }

    async validatePassword(password: string): Promise<boolean> {
        return bcrypt.compare(password, this.password);
    }
}

Solution

  • i found the answer myself,

    i did this in my async create on UsersService:

    constructor(
        @InjectRepository(User) private userRepository: Repository<User>
      ){}   //and i add this constructor to use Repository
    
    async create(createUserDto: CreateUserDto) {
        const user = this.userRepository.create({
          ...createUserDto // this is the change
        });
        
        await user.save();
    
        delete user.password;
        return user;
      }
    

    and then it resolve the error!