gpt4 book ai didi

typescript - 如何使用typeorm将可为空的数据库字段设置为NULL?

转载 作者:行者123 更新时间:2023-12-03 13:59:07 35 4
gpt4 key购买 nike

这似乎是一个很容易回答的问题,但找到答案似乎是不可能的。
我正在使用 Express 和 Typescript 为后端应用程序构建密码重置功能。我在数据库中使用 Postgres,在数据操作中使用 Typeorm。我的数据库中有一个包含这两列的 User 实体:

@Column({
unique: true,
nullable: true,
})
resetPasswordToken!: string;

@Column({ nullable: true, type: 'timestamp with time zone' })
resetPasswordExpiresAt!: Date;
当用户请求密码重置 token 时, resetPasswordToken 和 resetPasswordExpiresAt 字段都会填充所需的值。使用发送到用户电子邮件地址的 token ,用户可以重置他/她的密码。重置用户密码后,我想通过将它们设置为空来清除这两个字段:
user.resetPasswordToken = null;
user.resetPasswordExpiresAt = null;
user.save()
但是,如果我这样做,Typescript 会提示我分配空值的两行:

Type 'null' is not assignable to type 'string'.



Type 'null' is not assignable to type 'Date'.


如果我更改实体中的列以接受如下所示的 null,错误就会消失:
resetPasswordToken!: string | null;
...
resetPasswordExpiresAt!: Date | null;
但是,当我启动 Express 应用程序时,Typeorm 尝试连接到我的数据库时出现以下错误:

Data type "Object" in "User.resetPasswordToken" is not supported by "postgres" database.



如何将这些字段设置为空?

最佳答案

经过一夜的休息,我设法解决了我的问题。
Typeorm 根据您在 typescript 中为实体提供的变量的类型设置数据库字段的类型。 Typeorm 将下面的代码转换为我的 postgres 数据库中的 varchar 字段,因为我在 typescript 中给了它一个字符串作为类型。

@Column({
unique: true,
nullable: true,
})
resetPasswordToken!: string;
这也是我的问题所在。 Typeorm 接受字段的类型并尝试根据它读取的类型创建该数据库字段。虽然下面的代码是正确的,但 typescript 基本上将两种类型都封装在一个对象中,并且该对象是 Typeorm 正在读取的对象,导致我得到错误。
resetPasswordToken!: string | null;
为了解决我的问题,我必须像这样明确指定数据库字段类型:
@Column({
type: 'text',
unique: true,
nullable: true,
})
resetPasswordToken!: string;

关于typescript - 如何使用typeorm将可为空的数据库字段设置为NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64635617/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com