如何判断使用Prisma更新评论是否成功?
验证Prisma评论更新操作的执行状态
1. 确认目标评论是否存在
Prisma的update方法如果找不到符合where条件的记录,会直接抛出错误码为P2025的PrismaClientKnownRequestError。你可以通过捕获这个错误来判断评论是否存在:
let updatedComment; try { updatedComment = await this.ps.comment.update({ where: { id: commentId, userId: user.id, }, data: { body, }, include: { user: { select: { id: true, name: true, }, }, }, }); } catch (error) { if (error.code === 'P2025') { // 没有找到符合条件的评论 console.log('目标评论不存在,或不属于当前用户'); return; } // 处理其他类型的错误 throw error; }
2. 确认更新是否完成
有两种简单的方式验证更新是否生效:
- 对比返回值:直接检查返回的
updatedComment.body和你传入的body是否一致,因为Prisma返回的是更新后的完整记录,一致就说明更新成功。 - 改用
updateMany方法:这个方法不会因为找不到记录而抛错,而是返回一个包含count字段的对象,count的值就是实际更新的记录数。如果count === 1,说明成功更新了目标评论;如果count === 0,说明没有找到符合条件的记录:
const updateResult = await this.ps.comment.updateMany({ where: { id: commentId, userId: user.id, }, data: { body, }, }); if (updateResult.count === 0) { console.log('目标评论不存在,或不属于当前用户'); } else { console.log('评论更新成功'); // 如果需要更新后的评论详情,可以再执行一次findUnique查询 const updatedComment = await this.ps.comment.findUnique({ where: { id: commentId }, include: { user: { select: { id: true, name: true, }, }, }, }); }
内容的提问来源于stack exchange,提问作者Md. A. A. Apu
相关产品推荐
相关产品推荐

