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

如何在Prisma中更新复合类型模型?

Prisma复合类型模型更新报错解决

问题场景

你的数据结构示例:

{
  "name":"toy",
  "data":{
     "sports":{
        "currentState":"false"
    },
     "business":{
        "currentState":"false"
    }
  }
}

当前更新代码:

const updatedSource = await prisma.sources.update({
  where: {
    name: 'toy'
  },
  data: {
    data: {
      sports: {
        currentState: "true"
      }
    }
  },
})

Prisma Schema定义:

type SourcesData {
  business      SourcesDataState
  sports        SourcesDataState
}

type SourcesDataState {
  currentState StateData[]
}

type StateData {
  title String
  url   String
}

model sources {
  id           String   @id @default(auto()) @map("_id") @db.ObjectId
  data         SourcesData
  name         String   @unique
}

执行后报错:

Unknown arg `sports` in data.data.sports for type SourcesDataUpdateEnvelopeInput. Did you mean `set`? Available args:

解决方法

Prisma对嵌套复合类型的更新必须使用操作符,不能直接赋值,常见操作符有set(完全替换)或update(嵌套更新,保留其他字段)。

方案1:完全替换sports对象

如果需要直接替换整个sports对象,修改代码如下:

const updatedSource = await prisma.sources.update({
  where: {
    name: 'toy'
  },
  data: {
    data: {
      set: {
        sports: {
          currentState: "true" // 注意:Schema中currentState定义为StateData数组,这里字符串格式不匹配,需调整为数组,比如 [{title: "示例标题", url: "示例链接"}]
        }
      }
    }
  },
})

方案2:嵌套更新(保留原有business字段)

如果只想更新sports下的currentState,同时保留data内的其他字段,使用嵌套更新操作符:

const updatedSource = await prisma.sources.update({
  where: {
    name: 'toy'
  },
  data: {
    data: {
      update: {
        sports: {
          set: {
            currentState: "true" // 同样需注意Schema类型匹配问题
          }
        }
      }
    }
  },
})

额外注意点

你的Schema中SourcesDataState.currentState定义为StateData[]数组类型,但数据示例里用了字符串"false",这会导致类型不匹配,需修正数据格式为数组结构,例如:

"sports": {
  "currentState": [{"title": "状态标题", "url": "状态链接"}]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:50:23