2
votes

Hi I'm using NestJs with TypeOrm and currently connected to a MongoDB (but I want to be independent because most customers use MSSQL and Postgres databases).

Basically I want to store a key/value pair to the database. Both are of type String. This is the mapping entity holding the pair

@Entity()
export class Mapping extends BaseEntity {
  @PrimaryColumn()
  key: string;

  @Column()
  value: string;
}

The repository is currently empty

@EntityRepository(Mapping)
export class MappingsRepository extends Repository<Mapping> {}

In my service file I try to find a value by its key

  public async getValueByKey(key: string): Promise<string> {
    const mapping: Mapping = await this.mappingsRepository.findOne(key);

    if (!mapping) {
      throw new NotFoundException(`Key ${key} does not exist`);
    }

    return mapping.value;
  }

Unfortunately the findOne function always throws this error when passing in a key

Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

How can I fix this so that I can pass in any keys of type String? The parameter key is defined, I tried it with dummy values like f or ffsdagsdgfdg

2
What is the value of key? Make sure it's defined.yomateo
It is defined. I tested it with random strings. So the parameter itself comes with a random string which is not emptyhrp8sfH4xQ4

2 Answers

1
votes

Can you try

await this.mappingsRepository.findOne({key});

My guess it that typeorm doesn't understand primary key other than id

0
votes

findOne for mongo means it will search document by property _id and not your key because, mongo, by default, always add this _id as unique validator for each document so, you should provide a query to that method like it is defined in itssajan answer

but i think your use case of TypeORM is not the best, because it is made to work with SQL dbs, and not NoSQL dbs