4

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vasanth Kumar
  • 99
  • 1
  • 6

4 Answers4

6

You should use findOneBy

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

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;
  }
Vasanth Kumar
  • 99
  • 1
  • 6
0

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.

fmi21
  • 485
  • 3
  • 15
0

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

import { FindOptionsWhere } from 'typeorm';

...

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