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

如何在Prisma ORM中存储对象数组?NestJS场景代码修正

问题场景

我基于Prisma ORM与NestJS开发时,需要在Prisma中存储对象数组,编写的初始模型如下:

model User {
  id         String     @id @default(uuid())
  firstName  String
  lastName   String
  email      String     @unique
  password   String
  isVerified Boolean
  isActive   Boolean
  createdAt  DateTime   @default(now())
  updatedAt  DateTime   @default(now())
  avatar     String?
  companyId  String
  schedule   Json[] 
  Company    Company    @relation(fields: [companyId], references: [id], onDelete: Cascade)
  Problem    Problem[]
  Payments   Payments[]
}

执行以下创建用户的代码时出现报错:

const user = await this.prismaService.user.create({
    data: {
      email,
      firstName,
      lastName,
      password: hashedPassword,
      isActive: true,
      isVerified: false,
      companyId: company.id,
      schedule: [{
        key:"value1",
        key2:"value2"
      }],
    },

修正方案

Prisma的Json类型本身支持存储对象数组,无需额外声明为Json[],具体修正如下:

修正后的Prisma模型

model User {
  id         String     @id @default(uuid())
  firstName  String
  lastName   String
  email      String     @unique
  password   String
  isVerified Boolean
  isActive   Boolean
  createdAt  DateTime   @default(now())
  updatedAt  DateTime   @default(now())
  avatar     String?
  companyId  String
  schedule   Json // 修正为单个Json类型,即可存储对象数组
  Company    Company    @relation(fields: [companyId], references: [id], onDelete: Cascade)
  Problem    Problem[]
  Payments   Payments[]
}

修正后的创建代码(补充缺失的闭合括号)

const user = await this.prismaService.user.create({
    data: {
      email,
      firstName,
      lastName,
      password: hashedPassword,
      isActive: true,
      isVerified: false,
      companyId: company.id,
      schedule: [{
        key:"value1",
        key2:"value2"
      }],
    },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:32:47