node.jsnestjstypeormnode-mongodb-nativenode.js-typeorm

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


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


Solution

  • 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;
      }