Home > front end >  How do i store custom object in prisma schema?
How do i store custom object in prisma schema?

Time:12-16

I have a model called "Setup"

model Setup {
  id String @id @default(auto()) @map("_id") @db.ObjectId

  userId String? @unique @db.ObjectId
  user   User?   @relation(fields: [userId], references: [id])

  contract String[]
  legal    String[]

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

In this model i want to store an array like

const contractData = {
    id: '729a4839f3dapob44zt2b4b1',
    name: 'Example Name',
    text: 'Example Text'
}

so in my above model "Setup" i want to store the contractData

prisma.setup.create({
    data: {
      userId: '6399bc74426f71f2da6e316c',
      personal: [],
      contract: contractData,
      legal: []
    }
  })

Unfortunately, this not work.

How can i define an Object for contract and store this in my database?

CodePudding user response:

If you want to store a raw JSON, check out this guide: https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields

You will want to use the Json in Prisma in order to be able to store a raw JSON object (or multiple JSON objects as an array.)

model Setup {
  id String @id @default(auto()) @map("_id") @db.ObjectId

  userId String? @unique @db.ObjectId
  user   User?   @relation(fields: [userId], references: [id])

  contract Json[]
  legal    String[]

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Your Prisma prisma.setup.create query would basically be the exact same. Note that querying for what's in this JSON will be trickier - I would recommend creating a new model and then connecting it to the Setup model, but that if that isn't an option you can still perform some limited queries on the contract field.

Docs: https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filter-on-a-json-field

CodePudding user response:

In order to store an object in the contract field, you will need to change the type of the contract field from String[] to Object[].

model Setup {
  id String @id @default(auto()) @map("_id") @db.ObjectId

  userId String? @unique @db.ObjectId
  user   User?   @relation(fields: [userId], references: [id])

  contract Object[]
  legal    String[]

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

store an object in the contract field like

prisma.setup.create({
  data: {
    userId: '6399bc74426f71f2da6e316c',
    personal: [],
    contract: [contractData],
    legal: []
  }
})

contract field is now an array, so you will need to pass the object as an element of the array, like [contractData]

  • Related