How to Insert To and Delete From Arrays in Prisma
How can we update an array of values using Prisma?
Suppose we have a User
model that has a dogs
array of type String[]
.
model User {
id String @id @default(cuid())
dogs String[]
}
What is a simple way to update this array in Prisma?
Let’s say we want to update the dogs
array of the user with an id
of userId
.
We can easily modify an array using set
.
However, we’ll first have to query the user
database to obtain the array.
Add to beginning or end of array in Prisma
We can easily use the spread operator to add an element to an array.
const { dogs } = await prisma.user.findOne({
where: { id: userId },
select: { dogs: true },
});
await prisma.content.update({
where: { id: userId },
data: {
dogs: {
set: [...dogs, 'corgi']
},
},
});
We can modify the spread operator to add to the beginning of the array.
set: ['corgi', ...dogs]
Insert element into array in Prisma
We can insert an element using the spread operator as well.
The following is a simple utility function to insert elements into an array by index.
const insert = (arr, index, ...newItems) => [
...arr.slice(0, index),
...newItems,
...arr.slice(index)
];
We can use it like so:
const { dogs } = await prisma.user.findOne({
where: { id: userId },
select: { dogs: true },
});
await prisma.content.update({
where: { id: userId },
data: {
dogs: {
set: insert(dogs, 2, 'corgi')
},
},
});
Feel free to read up on array insertions by index.
Delete element from array in Prisma
We can use a simple filter to delete elements from an array.
const { dogs } = await prisma.user.findOne({
where: { id: userId },
select: { dogs: true },
});
await prisma.user.update({
where: { id: userId },
data: {
dogs: {
set: dogs.filter((id) => id !== 'corgi'),
},
},
});