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

使用TypeScript与Prisma ORM调用findUnique()时的类型错误问题

解决Prisma findUnique()中Int类型id与字符串路由参数不匹配的问题

问题核心

你遇到的问题本质是Next.js动态路由参数默认是字符串类型,但你的Prisma模型里id定义为Int类型——虽然你在ProductPageProps里把params.id声明为number,但运行时实际传入的是字符串,导致Prisma触发类型验证错误。你后续尝试转字符串并改字段名的操作是错误的,因为Prisma的查询条件只认模型中定义的字段(这里是id)。

解决方案步骤

1. 修正参数类型声明

首先把ProductPageProps里的params.id改为string,因为Next.js动态路由的参数始终是字符串:

interface ProductPageProps {
  params: {
    id: string; // 修正为string类型
  };
}

2. 在查询前将字符串转为数字

在getProduct函数中,把传入的字符串id转为整数,同时处理无效数字的情况(比如用户输入非数字id):

const getProduct = cache(async (id: string) => {
  // 转为十进制整数,避免进制解析错误
  const numericId = parseInt(id, 10);
  
  // 检查转换是否有效,无效则返回404
  if (isNaN(numericId)) {
    notFound();
  }

  const product = await prisma.product.findUnique({ 
    where: { id: numericId } // 传入转换后的数字id
  });
  if (!product) notFound();
  return product;
});

3. 同步其他调用逻辑

因为getProduct现在接收string类型的id,直接使用修正后的ProductPageProps参数即可,无需额外修改generateMetadata和ProductPage组件的调用逻辑:

// generateMetadata无需修改,直接传入params.id
export async function generateMetadata({
  params: { id },
}: ProductPageProps): Promise<Metadata> {
  const product = await getProduct(id);
  // 其余代码不变
}

// ProductPage组件同理
export default async function ProductPage({
  params: { id },
}: ProductPageProps) {
  const product = await getProduct(id);
  // 其余代码不变
}

为什么之前的尝试失败?

  • 最初你把params.id声明为number,但Next.js不会自动将路由参数转为数字,运行时实际传入的是字符串,导致Prisma收到不符合Int类型要求的值,触发验证错误。
  • 后续你尝试用stringId作为查询字段,这完全错误——你的Prisma模型中根本没有stringId这个字段,Prisma的类型系统会直接抛出字段不存在的错误。

内容的提问来源于stack exchange,提问作者The Elina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 05:48:24