Express API中PATCH未传dateofbirth时Prisma将其设为null的问题求助
解决方案
1. 修正入参类型,允许dateofbirth可选
首先,将customerNewInfo中的dateofbirth字段改为可选类型,匹配PATCH请求仅传递部分更新字段的语义:
// 原必填类型改为可选 customerNewInfo: {firstname: string, lastname: string, email: string, dateofbirth?: string}
2. 条件构建更新数据,避免空值覆盖
在构建Prisma的data参数时,仅当dateofbirth存在时才转换为Date并传入该字段。Prisma会忽略未包含在data中的字段,从而保留数据库原有的值:
写法一:分步构建更新对象
export async function editCustomer(id: number, customerNewInfo: {firstname: string, lastname: string, email: string, dateofbirth?: string}) { // 初始化基础更新数据 const updateData = { firstname: customerNewInfo.firstname, lastname: customerNewInfo.lastname, email: customerNewInfo.email, }; // 仅当dateofbirth存在时,转换为Date并添加到更新对象 if (customerNewInfo.dateofbirth) { updateData.dateofbirth = new Date(customerNewInfo.dateofbirth); } await prisma.customers.update({ where: { id }, data: updateData, }); }
写法二:对象扩展语法(更简洁)
export async function editCustomer(id: number, customerNewInfo: {firstname: string, lastname: string, email: string, dateofbirth?: string}) { await prisma.customers.update({ where: { id }, data: { firstname: customerNewInfo.firstname, lastname: customerNewInfo.lastname, email: customerNewInfo.email, // 条件扩展:仅当dateofbirth存在时才传入该字段 ...(customerNewInfo.dateofbirth && { dateofbirth: new Date(customerNewInfo.dateofbirth) }), }, }); }
原理说明
- Prisma的
update操作遵循仅更新传入字段的规则:如果data对象中不包含某个字段,数据库中该字段的原有值会被保留,不会被覆盖为null。 - 通过类型修改,让TypeScript允许
dateofbirth字段缺失;通过条件判断,仅在字段存在时才执行日期转换并传入,既满足数据库datetime类型的要求,又避免了空值覆盖问题。
可选优化:日期合法性验证
如果需要确保传入的dateofbirth是合法的日期字符串,可以在转换前添加验证逻辑:
if (customerNewInfo.dateofbirth) { const date = new Date(customerNewInfo.dateofbirth); if (!isNaN(date.getTime())) { updateData.dateofbirth = date; } else { throw new Error("Invalid date of birth format"); } }
内容的提问来源于stack exchange,提问作者SimbaNinja
相关产品推荐
相关产品推荐

