Argument of type '{ id: string; }' is not assignable to parameter of type 'FindOneOptions<Seller>'

Viewed 746

Using mongodb by typeorm with nestjs - create crud rest api

When trying to get data by findone() with 'id' . getting below error

TS2345: Argument of type '{ id: string; }' is not assignable to parameter of type 'FindOneOptions'.
Object literal may only specify known properties, and 'id' does not exist in type 'FindOneOptions'.

Code:

 const result = await this.sellerRepository.findOne({ id });

Entity

@Entity('seller')
export class Seller {
  @ObjectIdColumn()
  id: ObjectID;
  @Column({
    type: 'string',
    nullable: false,
    name: 'product_name',
  })
  productName: string;
  @Column({
    name: 'short_desc',
  })
}

async findOne(id: string): Promise<Seller> {
    const result = await this.sellerRepository.findOne({ id });
    return result;
  }

enter image description here

4 Answers

You can use fithOneBy({id}) or findOne(id). The signature you provided does not match any method provided by TypeORM, so that's why Typescript complains.

You can always check all available options here and here.

You should use findOneBy

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

Here is my solution for above..

I used new ObjectID(id) and import { ObjectID } from 'mongodb';

if you get error like TS7016: Could not find a declaration file for module 'mongodb'

then follow below steps

  1. create folder with 'typings'any at root project
  2. create index.d.ts
  3. add declare module 'mongodb';
  4. add path of the index.d.ts in tsconfig.json file under typeRoots as below

"typeRoots": [ "./typings", "./node_modules/@types/" ]

sample code

import { ObjectID } from 'mongodb';
 async findOne(id: string): Promise<Seller> {
    const result = await this.sellerRepository.findOne(new ObjectID(id));
    return result;
  }

You can use exported types from 'typeorm' like this:

import { FindOptionsWhere } from 'typeorm';

...

const result = await this.sellerRepository.findOne({ id: id as FindOptionsWhere<Seller> });
Related