Victor Motogna
Victor Motogna

Reputation: 830

Nest JS & TypeORM cannot use findOne properly

I am trying to get a user instance based on id (same happens for other attributes such as email. Inside the Service, this is my code:

@Injectable()
export class UserService {
  @InjectRepository(User)
  private readonly repository: Repository<User>;

  async findOne(id: number): Promise<User> {
    const user = await this.repository.findOne(id);
    return user;
  }
}

and my User entity is:

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column({ type: 'varchar', length: 120 })
  public name: string;

  @Column({ type: 'varchar', length: 120 })
  public email: string;
}

The problem is that I always get this error: src/api/user/user.service.ts - error TS2559: Type 'number' has no properties in common with type 'FindOneOptions<User>'.

Other methods such as getAll work just fine:

public getAllUsers(): Promise<User[]> {
  return this.repository.find();
}

Upvotes: 7

Views: 15612

Answers (6)

Muratcan Yusufoğlu
Muratcan Yusufoğlu

Reputation: 31

findOne(id) signature was dropped. Use following syntax instead:

const user = await userRepository.findOneBy({
    id: id // where id is your column name
})

According to the latest version of Typeorm, findOne expression has been changed as above.

Upvotes: 3

Shamir Imtiaz
Shamir Imtiaz

Reputation: 183

Actually you don't need to downgrade the typeorm package. Just changed to findOne by this:

async findOne(id: number): Promise<User> {
    const user = await this.repository.findOne({
           where: { id }
    });
    return user;
}

Upvotes: 3

Ahmed El-Beltagy
Ahmed El-Beltagy

Reputation: 99

the problem is the typeorm version , try typeorm version 0.2.25 and it will be works

Upvotes: 0

Sanan Ali
Sanan Ali

Reputation: 3427

There are some breaking changes in typeorm. I wouldn't suggest downgrading, instead check the latest methods.

findOne(id); is now changed to

findOneBy({
id: id // where id is your column name
})

And find() is now

find({
  select: {
    id: true,
    email: true,
    password: true,
  },
});

Please check this link for more information.

Upvotes: 12

check-in your package.json file and replace your version of typeorm with this one "typeorm": "^0.2.34"

Upvotes: 0

Micael Levi
Micael Levi

Reputation: 6665

are you using the latest version of typeorm? Then downgrade it to [email protected] because @nestjs/[email protected] might not support the latest one yet. You can read the changes of [email protected] here: https://github.com/typeorm/typeorm/releases/tag/0.3.0

Upvotes: 7

Related Questions