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

Prisma更新操作抛出类型错误:findMany与update条件一致却失败

Prisma更新CoinTransaction记录失败问题解决

问题场景

尝试用Prisma更新CoinTransaction记录时,findMany能通过paymentId匹配到记录,但update用完全相同的where条件却报错。相关代码如下:

const transaction = await prisma.coinTransaction.findMany({
    where: {
        paymentId: paymentIntent.id
    },
    select: {
        paymentId: true
    }
});
if (transaction.length > 1) {
    console.log('Error not unique')
} else {
    console.log('transaction: ', transaction[0])
    await prisma.coinTransaction.update({
        where: {
            paymentId: paymentIntent.id
        },
        data: {
            checkoutSessionCompleted: new Date()
        }
    })
}

VSCode报错信息:

Type '{ paymentId: any; }' is not assignable to type 'CoinTransactionWhereUniqueInput'.
  Object literal may only specify known properties, and 'paymentId' does not exist in type 'CoinTransactionWhereUniqueInput'.ts(2322)
index.d.ts(11553, 5): The expected type comes from property 'where' which is declared here on type '{ select?: CoinTransactionSelect | null | undefined; include?: CoinTransactionInclude | null | undefined; data: (Without<CoinTransactionUpdateInput, CoinTransactionUncheckedUpdateInput> & CoinTransactionUncheckedUpdateInput) | (Without<...> & CoinTransactionUpdateInput); where: CoinTransactionWhereUniqueInput; }'

问题原因

Prisma的update方法要求where参数必须传入唯一标识字段(对应CoinTransactionWhereUniqueInput类型)——也就是模型中被标记为@id或@unique的字段。你的paymentId没有被设置为唯一约束,因此不属于该类型的合法属性,导致类型不匹配。

解决方案

根据业务需求选择以下任意一种方案:

方案1:将paymentId设为唯一字段(推荐,若业务允许)

修改Prisma Schema,给paymentId添加@unique约束:

model CoinTransaction {
  id                  Int      @id @default(autoincrement())
  paymentId           String   @unique // 添加唯一约束
  checkoutSessionCompleted DateTime?
  // 其他模型字段...
}

修改完成后,执行npx prisma generate重新生成Prisma客户端,之后就能直接用paymentId作为update的where条件。

方案2:使用updateMany替代update

如果paymentId不保证唯一,但你已经通过findMany确认当前只有一条匹配记录,可改用updateMany方法(它支持普通的where条件,无需唯一标识):

// 替换原update代码
await prisma.coinTransaction.updateMany({
  where: {
    paymentId: paymentIntent.id
  },
  data: {
    checkoutSessionCompleted: new Date()
  }
})

方案3:用记录的唯一ID进行更新

从findMany返回的结果中获取记录的id(模型默认的唯一标识),用它作为update的where条件:

console.log('transaction: ', transaction[0])
await prisma.coinTransaction.update({
  where: {
    id: transaction[0].id // 使用唯一id字段
  },
  data: {
    checkoutSessionCompleted: new Date()
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:01:15