Next.js单路由实现两类PUT请求:增删defaultValues与exwork
解决Next.js单路由实现两类PUT增删操作的方案
核心思路
在单个PUT路由中,通过请求体传递操作标识(操作目标:defaultValues/exwork,动作:add/remove),根据标识执行对应的MongoDB增删逻辑($push添加数组项,$pull移除指定项)。
具体实现步骤
1. 修改路由文件(app/api/xxx/route.js)
整合两类操作的逻辑,通过请求体参数区分操作:
import { NextResponse } from 'next/server'; import CargoDetails from '@/models/CargoDetails'; import { ObjectId } from 'mongoose'; export async function PUT(request) { // 获取URL参数中的记录ID const recordId = request.nextUrl.searchParams.get("id"); // 解析请求体中的操作参数 const { type, action, itemId } = await request.json(); // 基础参数校验 if (!recordId || !type || !action) { return NextResponse.json({ error: "缺少必要参数" }, { status: 400 }); } let updateQuery = {}; // 根据操作类型和动作生成MongoDB更新语句 switch (true) { // 添加defaultValues项 case type === "defaultValues" && action === "add": updateQuery.$push = { defaultValues: { count: "", long: "", width: "", weight: "", high: "" } }; break; // 移除指定defaultValues项 case type === "defaultValues" && action === "remove": if (!itemId) { return NextResponse.json({ error: "需传入要删除的项ID" }, { status: 400 }); } updateQuery.$pull = { defaultValues: { _id: new ObjectId(itemId) } }; break; // 添加exwork项 case type === "exwork" && action === "add": updateQuery.$push = { exwork: { cost: "" } }; break; // 移除指定exwork项 case type === "exwork" && action === "remove": if (!itemId) { return NextResponse.json({ error: "需传入要删除的项ID" }, { status: 400 }); } updateQuery.$pull = { exwork: { _id: new ObjectId(itemId) } }; break; default: return NextResponse.json({ error: "不支持的操作类型" }, { status: 400 }); } try { // 执行更新并返回最新数据 const result = await CargoDetails.findOneAndUpdate( { _id: recordId }, updateQuery, { new: true } ); if (!result) { return NextResponse.json({ error: "未找到对应记录" }, { status: 404 }); } return NextResponse.json({ result }, { status: 200 }); } catch (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } }
2. 前端调用示例
对应添加/移除按钮的请求逻辑:
// 添加defaultValues项 async function addDefaultValue(recordId) { const res = await fetch(`/api/cargo-details?id=${recordId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ type: "defaultValues", action: "add" }) }); const data = await res.json(); // 更新前端状态(比如刷新列表) } // 移除defaultValues项(itemId为数组项的_id) async function removeDefaultValue(recordId, itemId) { const res = await fetch(`/api/cargo-details?id=${recordId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ type: "defaultValues", action: "remove", itemId }) }); const data = await res.json(); // 更新前端状态 } // exwork的增删逻辑同理,只需修改type为"exwork"
关键注意事项
- MongoDB数组项的_id:你的Schema中
defaultValues和exwork是数组类型,MongoDB会自动为每个数组元素生成_id,这是精准移除指定项的前提。 - 参数校验:路由中必须校验必要参数,避免无效请求。
- 错误处理:添加
try-catch捕获数据库操作异常,返回明确的错误信息和状态码。
内容的提问来源于stack exchange,提问作者Charvi
相关产品推荐
相关产品推荐

