【问题标题】:Express API Patch date returning null in PrismaExpress API 补丁日期在 Prisma 中返回 null
【发布时间】:2022-11-01 17:08:33
【问题描述】:

这是我的问题:我有一个PATCH API 请求,它正在替换我的PostgreSQL 表中现有的dateofbirth 条目,而不是在PATCH 正文中提供dateofbirth 时(编辑其他字段时) (例如firstname)。

在我的PostgreSQLCustomers 表中,dateofbirth 字段属于datetime 类型。 下面用typescript 编写的Prisma 函数对我的PostgreSQL 客户表执行Update

  export async function editCustomer(id: number, customerNewInfo: {firstname: string, lastname: string, email: string, dateofbirth: string}) {
    await prisma.customers.update({
   where: {
    id: id
  },
      data: {
        firstname: customerNewInfo.firstname,
        lastname: customerNewInfo.lastname,
        email: customerNewInfo.email,
        dateofbirth: new Date(customerNewInfo.dateofbirth)

      },
    })
  }

你可以猜到,当我没有提供dateofbirth 时,new Date(customerNewInfo.dateofbirth) 实际上是在将 null 传递给Prisma。如果我取出new Date(),那么我会在数据库端收到一个错误,说该字段是datetime,我提供了一个String

如何在发送 PATCH API 调用时强制使用 dateofbirth datetime 类型,同时不将现有条目替换为 null

【问题讨论】:

    标签: node.js postgresql express patch prisma


    【解决方案1】:

    如果有人想知道,这里是解决方案:

    dateofbirth: customerNewInfo.dateofbirth != null ? new Date(customerNewInfo.dateofbirth) : undefined
    

    这来自 Prisma 文档:

    将字段值设置为 undefined 与不包括 更新查询中的电子邮件字段

    来源:Prisma Client Documentation

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 2020-12-14
      • 2015-06-19
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多