Search code examples
nestjstypeorm

Nest.js TypeORM FindOneBy returns null even with data on the database


So I have this entity...

import { Column, Entity, PrimaryColumn } from "typeorm";

@Entity('Users')
export class User {
  @PrimaryColumn({ type: 'nvarchar', length: 36, unique: true })
  UserId: string;

  @Column({ type: 'nvarchar', length: 100, unique: true })
  Email: string;

  @Column({ type: 'nvarchar', length: 36 })
  CrmUserId: string;

  @Column({ type: 'nvarchar', length: 36, nullable: true })
  AzureB2CUserId: string;

  @Column({ type: 'bit', default: false })
  IsActive: boolean;

  @Column({ type: 'nvarchar', length: 100 })
  CreatedBy: string;

  @Column({ type: 'datetime' })
  CreatedDate: Date;

  @Column({ type: 'nvarchar', length: 100, nullable: true })
  UpdatedBy: string;

  @Column({ type: 'datetime', nullable: true })
  UpdatedDate: Date;
}

and using TypeORM I want to get one record by the email, not the UserId. So I had this on the repository.

public async getUserByEmail(email: string): Promise<User | null> {
  let _res = await this._userRepository.findOne({ where: { Email: email, IsActive: true }})
  return _res;
}

But it always returns a null, even if the record exists, I was thinking of doing it with a CreateQueryBuilder, like this...

public async getUserByEmail(email: string): Promise<User | null> {
    let _res = await this._userRepository.createQueryBuilder()
        .select()
        .from(User, "Users")
        .where('email = :emailParameter', { email })
        .getOne();
    return _res;
}

But the result is the same, I keep getting null, I have no idea what I am doing wrong, because it works if I use the primary key on the findOne and findOneBy. Any help out there with this?


Solution

    1. If you are using MongoDB then use import { MongoRepository, Repository } from 'typeorm'; for the _userRepository type.

    2. While using _userRepository findOneBy wrap the userId parameter in import { ObjectId } from 'mongodb' const query = {"_id":ObjectId(req.params.productId)}

    3. OR have a look at this example