如何在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
相关产品推荐
相关产品推荐

