#Insert `Map` as `Json`
4 messages · Page 1 of 1 (latest)
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:
- Convert the
Mapto a plain object:
const mapToObject = (map: Map<string, string>) => {
return Object.fromEntries(map.entries());
};
- 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.
✅ Great, thanks for letting us know that this solved your question!