小编Err*_*l59的帖子

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

这似乎是一个很容易回答的问题,但找到答案似乎是不可能的。

我正在使用 Express 和 Typescript 为后端应用程序构建密码重置功能。我在数据库中使用 Postgres,在数据操作中使用 Typeorm。我的数据库中有一个包含这两列的User实体:

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

@Column({ nullable: true, type: 'timestamp with time zone' })
resetPasswordExpiresAt!: Date;
Run Code Online (Sandbox Code Playgroud)

当用户请求密码重置令牌时,resetPasswordTokenresetPasswordExpiresAt字段都会填充所需的值。使用发送到用户电子邮件地址的令牌,用户可以重置他/她的密码。重置用户密码后,我想通过将它们设置为null来清除这两个字段:

user.resetPasswordToken = null;
user.resetPasswordExpiresAt = null;
user.save()
Run Code Online (Sandbox Code Playgroud)

但是,如果我这样做,Typescript 会抱怨我分配值的两行:

类型 'null' 不能分配给类型 'string'。

类型 'null' 不能分配给类型 'Date'。

如果我更改实体中的列以接受如下所示的null,错误就会消失:

resetPasswordToken!: string | null;
...
resetPasswordExpiresAt!: Date | null;
Run Code Online (Sandbox Code Playgroud)

但是,当我启动 Express 应用程序时,Typeorm 尝试连接到我的数据库时出现以下错误:

“postgres”数据库不支持“User.resetPasswordToken”中的数据类型“Object”。

 

如何将这些字段设置为null

postgresql express typescript typeorm

11
推荐指数
2
解决办法
1万
查看次数

标签 统计

express ×1

postgresql ×1

typeorm ×1

typescript ×1