简体   繁体   中英

How do i store custom object in prisma schema?

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?

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM