如何在 PostgreSQL 中保存生日日期?

问题描述 投票:0回答:2

我正在做一个 GraphQL 教程,我需要保存用户的生日。我正在使用 TypeORM、Apollo-server-express 和 PostgreSQL。

这些是我当前的用户实体和架构文件。我不知道如何保存/输入生日,所以我暂时做到了

nullable

// user.entity.ts

@Entity()
export class User extends BaseEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column('text')
  first_name: string;

  @Column('text')
  last_name: string;

  @Column({
    unique: true
  })
  @Length(5, 100)
  @IsEmail()
  email: string;

  @Column()
  password: string;

  @Column({
    nullable: true
  })
  birthday: Date;
}
// user.schmea.ts

  type User {
    id: ID!
    first_name: String
    last_name: String!
    email: String!
    birthday: Date
    created_at: Date @date(format: "HH:MM mmmm d, yyyy")
    updated_at: Date @date(format: "HH:MM mmmm d, yyyy")
  }

  input CreateUserInput {
    first_name: String
    last_name: String!
    email: String!
    password: String!
    birthday: Date
  }

这是我的示例

mutation
输入
createUser
:

mutation {
  createUser(data: {
    first_name: "Some",
    last_name: "One",
    email: "[email protected]",
    password: "hashThisPlease1"
  }) {
    id
    first_name
    last_name
    email
  }
}

我应该像

birthday
一样将
string
输入为
"1990-12-30"
吗?这是 PostgreSQL 中保存
birthday
列的标准方法吗?

node.js postgresql graphql apollo typeorm
2个回答
2
投票

生日通常保存为日期,并且大多数数据库(包括 Postgres)都支持日期(参见文档)。 您需要做的就是将生日装饰器更改为:

  @Column({
    type: 'date',
    nullable: true
  })
  birthday: Date | null;

0
投票

我绝不是专家,但我同意福吉法官的观点。 虽然我想补充一点,您可以选择将属性类型设置为“字符串”,如下所示:

@Column({ type: "date" })
date_of_birth: string;

然后你会得到(在我看来)更容易理解的错误消息:

"Datum/Zeit-Feldwert ist außerhalb des gültigen Bereichs: »1986-20-25«" 
("Date/Time field value is not in valid range")

而不是:

"ungültige Eingabesyntax für Typ date: »NaN-NaN-NaN«" 
("invalid input syntax for type date")

如果您输入:

"1986-02-30"
,属性类型为
"string"
,您将收到类似上面的错误,而属性类型为
"Date"
,由于 javascript 日期构造函数,它会将其转换为
"1986-03-02"

但是您可能会失去一些“模式透明度”,因为您要求的是“字符串”类型的值而不是“日期”,例如像我一样使用 TypeGraphQl 时 并在 Args/Input-Types 中实现实体部分。

最后,如果您的请求包含 DateObject 的 stringfied(到 JSON)实例,则在尝试使用 DateObject 构造函数初始化此实例时会捕获无效日期,因此您可以使用“Date”而不是“string” “,当使用这个(最后一个)方法时。

© www.soinside.com 2019 - 2024. All rights reserved.