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

如何向Prisma嵌套字段数组中添加对象元素?

Prisma嵌套数组字段push操作TypeScript报错修复

问题场景

使用Prisma的upsert方法更新用户嵌套字段shop.items数组时,直接推入单个对象元素触发TypeScript报错:

Object literal may only specify known properties, and 'name' does not exist in type '(...items: ItemCreateInput[]) => number'.

对应数据模型Schema:

model User {
  id   String @id @map("_id")
  shop Shop

  @@map("users")
}

type Shop {
  items Item[]
}

type Item {
  name String
}

修复方案

Prisma的push方法要求传入Item类型的数组,而非单个对象。修正后的代码如下:

await prisma.user.upsert({
  where: { id: "目标用户ID" },
  update: {
    shop: {
      items: {
        push: [{ name: "example" }] // 用数组包裹要推入的元素
      }
    }
  },
  create: {
    id: "目标用户ID",
    shop: {
      items: [{ name: "example" }]
    }
  }
});

原因说明

报错信息中的(...items: ItemCreateInput[]) => number明确提示,push是接受可变参数的函数,需要传入Item对象组成的数组。哪怕只推入单个元素,也必须用数组包裹。如果要批量添加多个元素,直接在数组中追加对象即可:

push: [{ name: "商品1" }, { name: "商品2" }]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:44:54