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

7.5k Views Asked by At

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

5

There are 5 best solutions below

0
Vasanth Kumar On BEST ANSWER

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;
  }
3
fmi21 On

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.

1
Alberto lopez jimenez On

You should use findOneBy

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

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

import { FindOptionsWhere } from 'typeorm';

...

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

Use it like this:

const prodId = await this.productEntity.findOne({
  where: {
    column_name_in_Entity: defined initializer
  }
})