Insert `Map` as `Json`

I have the schema
model Foo {
id Int @id @default(autoincrement())
fields Json
}
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?
2 Replies
Prisma AI Help
Prisma AI Helpā€¢2w ago
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());
};
const mapToObject = (map: Map<string, string>) => {
return Object.fromEntries(map.entries());
};
2. Use this function when inserting the data:
const dataToInsert = {
fields: mapToObject(yourMap)
};

await prisma.foo.create({
data: dataToInsert
});
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);
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. āœ… Great, thanks for letting us know that this solved your question!
Nurul
Nurulā€¢2w ago
@matteosantama Just checking to see if the Bot solution worked as expected for you šŸ™‚ Any feedback?

Did you find this page helpful?