Search code examples
mysqlnestjstypeorm

Unknown column '{columnName}' in 'where clause'


when using the typeorm repository functions findOne or the QueryBuilder like:

  constructor (
    @InjectRepository(EntityName)
    private entityNameRepository: Repository<EntityName>,
  ) {}

  ...

    const qb = this.entityNameRepository.createQueryBuilder('e');
    qb.where('e.originKey=:origin_key', {
      origin_key: originKey,
    });

    const entityName: EntityName = await qb.getOne();

    // or

    const entityName: EntityName = await this.entityNameRepository.findOne({
       originKey: originKey,
    });

I receive the following error message:

QueryFailedError: Unknown column 'originKey' in 'where clause'
    at new QueryFailedError (/Users/{project}/node_modules/typeorm/error/QueryFailedError.js:11:28)
    at Query.onResult (/Users/{project}/node_modules/typeorm/driver/mysql/MysqlQueryRunner.js:216:45)
    at Query.execute (/Users/{project}/node_modules/mysql2/lib/commands/command.js:30:14)
    at PoolConnection.handlePacket (/Users/{project}/node_modules/mysql2/lib/connection.js:425:32)
    at PacketParser.Connection.packetParser.p [as onPacket] (/Users/{project}/node_modules/mysql2/lib/connection.js:75:12)
    at PacketParser.executeStart (/Users/{project}/node_modules/mysql2/lib/packet_parser.js:75:16)
    at Socket.Connection.stream.on.data (/Users/{project}/node_modules/mysql2/lib/connection.js:82:25)
    at Socket.emit (events.js:182:13)
    at addChunk (_stream_readable.js:287:12)
    at readableAddChunk (_stream_readable.js:268:11)

My entity looks like:

import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { UuidGenerator } from '../adapter/uuid-generator';

@Entity()
export class EntityName extends BaseEntity {
  @PrimaryGeneratedColumn({ name: 'id' })
  id: number;

  @Column({ name: 'uuid', unique: true, nullable: false })
  uuid: string;

  @Column({ name: 'is_active', default: true })
  isActive: boolean;

  @Column({ name: 'origin_key', unique: true, nullable: true })
  originKey: string;
}

And the column in MySQL is called origin_key

And when I force to query with property name origin_key it also fails with a different error telling that this field isn't given in the entity, which makes sense due to the naming.


Solution

  • Edit: As always, the problem sits in front of the screen: the problem was the passed parameter: it wasn't a scalar value, instead it was an object like: { originKey: 111 } (expected was a string), so I was misled into the wrong direction, it's not about the definition. The error message pointed to the passed object and not the column/property of my entity.