如何使用Prisma单独更新模型中的各个字段?
实现Post对象单个字段独立更新的解决方案
问题根源
你的代码存在两个核心问题:
- 前端请求体格式错误:直接将
title字符串传入JSON.stringify(),导致后端收到的是纯字符串而非键值对对象,解构时无法正确获取字段值。 - 后端强制更新所有字段:无论前端传了哪些字段,都强制将
title、content、summary写入更新数据,未传字段会被解析为undefined,导致更新无效或错误覆盖原有内容。
修正方案
1. 前端:发送正确格式的请求体
更新单个字段时,需将字段包装为包含键名的对象,确保后端能识别要更新的目标字段。示例如下:
const updateTitleData = async () => { try { await fetch(`/api/story/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title }) // 传递包含字段名的对象,而非单个字符串 }) refreshData() } catch (error) { toast.error('Document could not be updated') console.error(error); } };
同理,更新content或summary时,只需将请求体改为{ content }或{ summary }即可。
2. 后端:仅更新前端传递的字段
无需强制指定所有三个字段,动态使用前端传来的有效字段进行更新。可以直接将req.body作为更新数据(前端仅传递需要更新的单个字段),或添加字段验证逻辑确保安全性:
const storyId = req.query.id; if (req.method !== 'PUT') { console.log("Note could not be modified"); res.status(400).json({ message: "Note could not be modified" }); } else { // 仅更新前端传递的字段,未传字段保持原有值 await prisma.story.update({ where: { id: storyId }, data: req.body }); res.status(200).json({ message: 'Updated successfully' }); }
如果需要更严谨的字段校验(仅允许更新指定字段),可提前构建合法的更新对象:
const allowedFields = ['title', 'content', 'summary']; const updateData = {}; // 只保留前端传来的合法字段 for (const field of allowedFields) { if (req.body[field] !== undefined) { updateData[field] = req.body[field]; } } await prisma.story.update({ where: { id: storyId }, data: updateData });
验证效果
修改后:
- 更新title时,前端发送
{ title: "新标题" },后端仅更新title字段,content和summary保持原有值; - 后续更新content时,前端发送
{ content: "新内容" },后端仅更新content字段,其他字段不受影响。
内容的提问来源于stack exchange,提问作者Shingai Munyuki
相关产品推荐
相关产品推荐

