Amiga500
Amiga500

Reputation: 6131

Nestjs/TypeORM - How to implement custom search by column

I am playing around with NestJs using TypeORM along with MySQL.

I have went via documentation, and I have made basic CRUD app running locally. I have built in searches (via Repository) by id, but I would need to implement search by custom column as well.

For example I have this entity:

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

  @Column()
  username: string;

  @Column()
  first_name: string;

  @Column()
  last_Name: string;

  @Column()
  gender: string;
  

And in my repository, I have these built in methods:

async findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  findOne(id: string): Promise<User> {
    return this.usersRepository.findOne(id);
  }
  

And it works just fine, as expected. I would need another custom search, so I can search also by username, how can I achieve that? I would need something like this:

findByUsername(username: string): Promise<User> {
    return this.usersRepository.findByUsername(username);
  }

I assume I have to implement custom query, but I have no clue where to do it :(

Upvotes: 5

Views: 40928

Answers (5)

Triskeriaki
Triskeriaki

Reputation: 11

I see that no one uses findOneBy, and it's the one working for me. Even if subject is old, may I add that alternative :

 async getUserByName(username: string){
    return await this.userRepository.findOneBy({name: username });
}

Find more on https://typeorm.io/working-with-repository

Upvotes: 0

user2430821
user2430821

Reputation: 39

You can use this code

findByName(user_name: string): Promise<User> {
    return this.usersRepository.findOne({ user_name }); 
}

Upvotes: 2

Allen Tim spam
Allen Tim spam

Reputation: 1

const firstUser = await connection
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getOne();

Upvotes: -2

andsilver
andsilver

Reputation: 5972

Here is the simpler solution:

findByUsername(username: string): Promise<User | undefined> {
    return this.usersRepository.findOne({ username }); 
}

Upvotes: 11

Amiga500
Amiga500

Reputation: 6131

I managed to achieve it, by using queryBuilder

So this is how my function looks now:

findByUsername(username: string): Promise<User | undefined> {
    const user = getRepository(User)
      .createQueryBuilder("user")
      .where("user.username = :username", { username: username })
      .getOne();

    return user;
  }

Upvotes: 0

Related Questions