You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS+TypeORM+MongoDB调用findOne传id报TS2345类型错误

报错原因

TypeORM 0.3.x 及以上版本调整了 Repository 层查询方法的入参规则,很多基于0.2.x版本的旧教程写法直接照搬就会触发TS2345错误,MongoDB场景下还有两个具体触发点:

  • findOne方法不再直接接收平铺的属性查询对象作为入参,查询条件需要包裹在where配置项中传入,也可以换用findOneBy方法直接接收查询条件对象
  • MongoDB主键默认存储为ObjectId类型,接口传入的字符串id和实体中定义的ObjectID类型不匹配,直接传值既过不了TS类型校验,实际运行时也会因为类型不一致匹配不到数据
修复方案
  1. 引入ObjectId转换工具,将传入的字符串id转为MongoDB可识别的ObjectId实例
  2. 调整查询方法的传参格式,匹配新版TypeORM的类型要求

修改后的完整查询逻辑代码如下:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ObjectId } from 'mongodb';
import { Seller } from './seller.entity'; // 替换为你实际的Seller实体引入路径

@Injectable()
export class SellerService {
  constructor(
    @InjectRepository(Seller)
    private readonly sellerRepository: Repository<Seller>,
  ) {}

  async findOne(id: string): Promise<Seller> {
    // 写法1:使用findOne,查询条件放在where配置项中
    const result = await this.sellerRepository.findOne({
      where: {
        id: new ObjectId(id),
      },
    });

    // 写法2:使用findOneBy直接传入查询条件,写法更简洁
    // const result = await this.sellerRepository.findOneBy({
    //   id: new ObjectId(id),
    // });

    return result;
  }
}

注意:不要通过// @ts-ignore等方式跳过TS校验直接传字符串id查询,运行时会因为字段类型不匹配,永远返回空结果。

内容的提问来源于stack exchange,提问作者Vasanth Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 20:39:17