I have a Prisma model with lets say 10 fields. Think User model with firstname, lastname, address, e-mail , phone, mobile, age etc.
I am trying to write a update method for this, where I most of the times only want to update some or only 1 of the fields. Not the whole User. If the field is not sent with the request, I want to keep the value from the db.
What would the best practice be for this. Should I check for all fields to be in the req object? How could I write this for prisma?
Example on how I would like it to work:
req = {firstname: 'Bob', email: '[email protected]', etc}
const updateUser = await prisma.user.update({
where: {
email: '[email protected]',
},
data: {
req.firstname ? (email: req.firstname) : null,
req.email ? (email: req.email) : null,
req.address? (email: req.address) : null,
},
})
Or should I check for values to be present in req and build the data object in 10 versions:
let customDataObject = {}
if (req.firstname) {
customDataObject.firstname = req.firstname
}
if (req.email) {
customDataObject.email= req.email
}
const updateUser = await prisma.user.update({
where: {
email: '[email protected]',
},
data: customDataObject,
})
CodePudding user response:
The undefined
property is used in Prisma to do exactly what you're trying to achieve. Basically, when a field is assigned undefined
it means ignore this and do nothing for this field. You can learn more about this in the article about null
and undefined
in the docs.
This is what your update query should look like.
// assuming email, firstname and address fields exist in your prisma schema.
const updateUser = await prisma.user.update({
where: {
email: '[email protected]',
},
data: {
firstname: req.firstname || undefined, // if req.firstname is falsy, then return undefined, otherwise return it's value.
email: req.email || undefined,
address: req.address || undefined
},
})