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

如何在JavaScript中通用引用对象属性实现Prisma动态更新

动态更新Prisma模型的任意属性

直接用JavaScript的计算属性名语法就能解决这个问题——把要更新的属性名存在变量里,在data对象中用方括号包裹变量名,就能实现动态指定属性。

单属性更新示例:

// 可以替换成任意合法的用户属性名,比如'name'/'age'
const targetProp = 'email';
const newValue = 'new-user@example.com';

const user = await prisma.user.update({
  where: { id: theid },
  data: {
    [targetProp]: newValue // 方括号包裹变量,实现动态属性名
  }
});

如果要批量更新多个属性,也可以先构建完整的更新对象:

const updateData = {};
updateData['name'] = 'New Username';
updateData['age'] = 28;

const user = await prisma.user.update({
  where: { id: theid },
  data: updateData
});

额外提示(TypeScript场景)

如果用TypeScript开发,为了避免传入无效属性名报错,可以给属性变量加类型约束:

type UserUpdatableProps = keyof Prisma.UserUpdateInput;
const targetProp: UserUpdatableProps = 'email'; // 只能传入User模型允许更新的属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:20:16