类型参数 '{ id: string; }' 不可分配给“FindOneOptions<Seller>”类型的参数

问题描述 投票:0回答:5

通过 typeorm 使用 mongodbnestjs - 创建 CRUD REST API

尝试通过 findone() 使用 'id' 获取数据时。低于错误

TS2345:类型参数 '{ id: string; }' 不可分配给“FindOneOptions”类型的参数。
对象文字只能指定已知属性,并且“FindOneOptions”类型中不存在“id”。

代码:

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

实体

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

node.js nestjs typeorm node-mongodb-native node.js-typeorm
5个回答
6
投票

你应该使用findOneBy

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

2
投票

这是我的上述解决方案..

我用了

new ObjectID(id)
并且
import { ObjectID } from 'mongodb';

如果出现类似 TS7016: Could not find a statements for module 'mongodb' 的错误

然后按照以下步骤操作

  1. 在根项目中创建带有“typings”any 的文件夹
  2. 创建索引.d.ts
  3. 添加
    declare module 'mongodb'
    ;
  4. 在下面的
    index.d.ts
    文件中添加
    tsconfig.json
    的路径
    typeRoots
    如下

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

示例代码

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

0
投票

您可以使用

fithOneBy({id})
findOne(id)
。您提供的签名与 TypeORM 提供的任何方法都不匹配,这就是 Typescript 抱怨的原因。

您可以随时在此处此处查看所有可用选项。


0
投票

您可以使用从“typeorm”导出的类型,如下所示:

import { FindOptionsWhere } from 'typeorm';

...

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

0
投票

像这样使用它

const prodId = 等待 this.productEntity.findOne({ 在哪里: { 产品ID:产品ID } })

© www.soinside.com 2019 - 2024. All rights reserved.