Search code examples
typescripttypeorm

Where clause as string in Find/FindOne TypeORM


I was searching and reading the docs, but coundn't find a solution.

Is there a way to set the where param as string in find/findOne method in TypeORM?

Because, it seems that TypeORM doesn't accept private attributes as a param in find/findOne methods, and I understand why.

For example, this is the class used:

import { Column } from 'typeorm';

@Entity()
export default class Client extends BaseEntity{
    ...

    @Column({ name: 'email', type: 'varchar', length: 64, unique: true })
    private _email: string;

    ...
}

This is the controller function:

...

async function testing(request: Request, response: Response, next: NextFunction) {
    const { name, email, password } = request.body;
    
    const existingClient = await Client.findOne({ _email: email });

    console.log(existingClient);
}

...

I thought creating something like:

await Client.findOne({`email = [email protected]`});

Is there a way to do this?


Solution

  • I would recommend to simply use it as public.

    When you really want to use private, you probably need to use the entitymanager:

    entityManager
        .createQueryBuilder(Client, "client")
        .where("client._email = :email", { email: '[email protected]' })
        .getOne();
    

    What is and how to add entityManager: https://typeorm.io/#/working-with-entity-manager