#Insert `Map` as `Json`

4 messages · Page 1 of 1 (latest)

thick gate
#

I have the schema

model Foo {
  id      Int   @id @default(autoincrement())
  fields  Json
}

and I'd like to insert records with type { fields: Map<String, String> }[]. However I'm getting an error Type 'Map<string, string>' is not assignable to type 'JsonNull | InputJsonValue'. How can I get around this?

crystal mossBOT
#

Skipping coffee for instant knowledge! Let's brew that AI answer now.

crystal mossBOT
# crystal moss Skipping coffee for instant knowledge! Let's brew that AI answer now.

To insert a Map<String, String> as a Json field in Prisma, you'll need to convert the Map to a plain JavaScript object before inserting it. Prisma's Json type doesn't directly support Map objects, but it can handle plain objects.

Here's how you can modify your code to insert the data:

  1. Convert the Map to a plain object:
const mapToObject = (map: Map<string, string>) => {
  return Object.fromEntries(map.entries());
};
  1. Use this function when inserting the data:
const dataToInsert = {
  fields: mapToObject(yourMap)
};

await prisma.foo.create({
  data: dataToInsert
});

This approach converts the Map to a plain object, which Prisma can then handle as a Json field.

It's important to note that when you retrieve this data later, it will be a plain object, not a Map. If you need to work with it as a Map again, you'll need to convert it back:

const objectToMap = (obj: Record<string, string>) => {
  return new Map(Object.entries(obj));
};

const retrievedFoo = await prisma.foo.findUnique({ where: { id: someId } });
const fieldsMap = objectToMap(retrievedFoo.fields);

This solution allows you to work with Map<String, String> in your application logic while storing and retrieving it as Json in the database.

For more information on working with JSON fields in Prisma, you can refer to the Working with Json fields documentation.

crystal mossBOT