Next.js Route Handlers结合Prisma更新数据库记录报错问题
问题:Next.js Route Handlers + Prisma 实现数据库记录更新失败
一、单条记录更新异常
实现代码
import prisma from "../../../../lib/prisma"; import { NextResponse } from "next/server"; export async function POST(req) { try { const { quantity, product_name } = req.json(); const productUpdate = await prisma.products.update({ where: { product_name: product_name, }, data: { quantity: quantity, }, }); const data = JSON.stringify(productUpdate); return NextResponse.json(data); } catch (error) { console.error("Error:", error); return NextResponse.error( "An error occurred while processing the request." ); } }
请求JSON
{ "quantity": 10, "product_name": "alfa Pen" }
报错信息
Error: PrismaClientValidationError: Invalid `prisma.products.update()` invocation: { where: { product_name: undefined, ? id?: Int }, data: { quantity: undefined } } Argument `where` of type ProductsWhereUniqueInput needs at least one argument. Available options are listed in green.
二、多条记录更新异常
调整后代码
import prisma from "../../../../lib/prisma"; import { NextResponse } from "next/server"; export async function POST(req) { try { const { quantity, product_name, price } = req.json(); const productUpdate = await prisma.products.updateMany({ where: { product_name: { contains: product_name, } }, data: { quantity: quantity, price: price, }, }); const data = JSON.stringify(productUpdate); return NextResponse.json(data); } catch (error) { console.error("Error:", error); return NextResponse.error( "An error occurred while processing the request." ); } }
返回结果
"{\"count\":0}"
三、Prisma Schema定义
generator client { provider = "prisma-client-js" previewFeatures = ["jsonProtocol", "fullTextSearch", "fullTextIndex"] } datasource db { provider = "postgresql" url = env("POSTGRES_PRISMA_URL") // uses connection pooling directUrl = env("POSTGRES_URL_NON_POOLING") // uses a direct connection } model Products { id Int @id @unique @default(dbgenerated("floor(random() * (9999 - 1000 + 1)) + 1000")) product_name String @unique @db.VarChar(50) product_description String @db.Text quantity Int @db.Integer price Decimal @db.Decimal() pproduct Category @relation(fields: [category_name], references: [category_name]) category_name String productsOrder_id Int ProductsOrder ProductsOrder[] } model Category { id Int @id @unique @default(dbgenerated("floor(random() * (9999 - 1000 + 1)) + 1000")) category_name String @unique @db.VarChar(50) products Products[] } model ProductsOrder { id Int @id @unique @default(dbgenerated("floor(random() * (9999 - 1000 + 1)) + 1000")) date DateTime @default(now()) quantity Int @db.Integer totalAmount Decimal @db.Decimal() products Products[] } model Service { id Int @id @unique @default(dbgenerated("floor(random() * (9999 - 1000 + 1)) + 1000")) serviceName String @db.VarChar(50) price Decimal @db.Decimal() ServiceOrder ServiceOrder[] } model ServiceOrder { id Int @id @unique @default(dbgenerated("floor(random() * (9999 - 1000 + 1)) + 1000")) quantity Int @db.Integer totalAmount Decimal @db.Decimal() services Service[] }
四、问题排查与解决方法
核心问题:未正确获取请求体
req.json()是异步方法,必须使用await才能拿到正确的JSON数据,之前的代码直接解构导致所有变量都是undefined,这是引发两个问题的根本原因。
修正后的单条记录更新代码
import prisma from "../../../../lib/prisma"; import { NextResponse } from "next/server"; export async function POST(req) { try { // 关键:添加await获取请求体 const { quantity, product_name } = await req.json(); // 可选:验证参数合法性 if (!product_name || typeof quantity !== 'number') { return NextResponse.json({ error: "参数错误" }, { status: 400 }); } const productUpdate = await prisma.products.update({ where: { product_name: product_name, }, data: { quantity: quantity, }, }); // 无需手动JSON.stringify,NextResponse.json会自动处理 return NextResponse.json(productUpdate); } catch (error) { console.error("Error:", error); return NextResponse.json( { error: "处理请求时发生错误" }, { status: 500 } ); } }
修正后的多条记录更新代码
import prisma from "../../../../lib/prisma"; import { NextResponse } from "next/server"; import { Decimal } from "@prisma/client/runtime/library"; export async function POST(req) { try { const { quantity, product_name, price } = await req.json(); // 参数验证 if (!product_name || typeof quantity !== 'number' || typeof price !== 'number') { return NextResponse.json({ error: "参数错误" }, { status: 400 }); } const productUpdate = await prisma.products.updateMany({ where: { product_name: { contains: product_name, // 可选:忽略大小写 mode: 'insensitive' } }, data: { quantity: quantity, // 注意:price是Decimal类型,需要转换 price: new Decimal(price), }, }); return NextResponse.json(productUpdate); } catch (error) { console.error("Error:", error); return NextResponse.json( { error: "处理请求时发生错误" }, { status: 500 } ); } }
额外注意事项
- Decimal类型处理:Schema中
price是Decimal类型,传入时需要用new Decimal(price)转换,否则可能导致类型不匹配。 - 参数验证:添加参数合法性检查能提前拦截非法请求,避免无效数据库操作。
- NextResponse.json用法:无需手动调用
JSON.stringify,该方法会自动序列化数据。 - 唯一性约束:
product_name是@unique字段,单条更新时用它作为where条件完全合法。
内容的提问来源于stack exchange,提问作者We_Go
相关产品推荐
相关产品推荐

