Prisma ORM has an implementation of the update or create upsert()
method and a group of
bulk requests,
but there is no such thing as .upsertMany()
, i.e. bulk "create or update existing records".
What is the best way to implement such a method using Prisma ORM?
Prisma ORM has an implementation of the update or create upsert()
method and a group of
bulk requests,
but there is no such thing as .upsertMany()
, i.e. bulk "create or update existing records".
What is the best way to implement such a method using Prisma ORM?
Share Improve this question asked Mar 9, 2022 at 10:58 Artyom IonashArtyom Ionash 4581 gold badge7 silver badges18 bronze badges3 Answers
Reset to default 17Prisma doesn't natively support upsertMany
.
There is a Feature Request to provide the upsertMany
method.
As of now the best approach would be to loop over the data and invoke upsert
in the loop along with using $transaction
.
Example:
const collection = await prisma.$transaction(
userData.map(cur =>
prisma.cur.upsert({
where: { id: cur.id },
update: {},
create: { id: cur.id },
})
)
)
Here's a reference to $transaction API which should be helpful.
You can use upsert to update multiple objects like the following: In the following example, I am updating a user's profile and upserting multiple addresses by using the map function.
await this.prisma.user.update({
where: {
id: user.id
},
data:{
fullName: saveUserProfileDto?.fullName,
email: saveUserProfileDto?.email,
userAddresses: {
upsert: saveUserProfileDto?.addresses?.map(address => ({
where: {
uuid: address.uuid || ""
},
create: {
uuid: uuidv4(),
country: address.country,
cityTown: address.cityTown,
streetAddress: address.streetAddress,
apartmentSuit: address.apartmentSuit,
},
update: {
country: address.country,
cityTown: address.cityTown,
streetAddress: address.streetAddress,
apartmentSuit: address.apartmentSuit,
}
}))
}
}
});
So you don't need to delete anything before upserting.
I do wonder if instead of using the $transaction
API and looping over the data, it would be more performant to check against the DB if each record should be inserted or updated and then use a createMany
along with updateMany
.