Prisma UPSERT Many
The UPSERT operation allows you to insert or update multiple records in a database table based on a specified condition. Prisma provides a handy method to perform UPSERTs on multiple records called upsertMany()
.
To use the upsertMany()
method, you need to define a unique attribute or a combination of attributes that can be used to determine whether a record already exists. Prisma will then check if each record with the specified attributes already exists in the database and either update the existing records or insert new ones, based on the condition you provide.
Example
Let’s assume we have a “users” table with the following columns: “id” (primary key), “name”, and “email”. We want to insert or update multiple user records at once.
Prisma Schema
model User {
id Int @id @default(autoincrement())
name String
email String @unique
}
Create or Update Users
const users = [
{
name: 'John Doe',
email: 'john@example.com'
},
{
name: 'Jane Smith',
email: 'jane@example.com'
}
];
async function createOrUpdateUsers() {
const result = await prisma.user.upsertMany({
where: {
OR: [
{ email: 'john@example.com' },
{ email: 'jane@example.com' }
]
},
create: users,
update: users
});
console.log(result);
}
createOrUpdateUsers()
.catch(error => {
console.error(error);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
In the above example, we define an array of user objects with their respective names and emails. The upsertMany()
method is then called with the following parameters:
where
: This specifies the condition to determine if a user record already exists. Here, we use the OR operator to match the email attribute of each user in the array.create
: The array of user objects to be created in case a record doesn’t exist.update
: The array of user objects to be updated in case a record already exists.
The upsertMany()
method returns an object that gives you information about the operation. You can handle the result according to your specific needs.