【发布时间】:2020-04-09 07:59:20
【问题描述】:
我无法将 SQL 的结果绑定到我在 Javascript /Typescript 中的模型。
在我的模型中,我的属性为 created_at,类型为 Date。
当我在 Postgres SQL 语句中使用 JSON 函数来避免关系的父行重复时,我会得到不同格式的时间戳。
这是一个简单的例子
SELECT
a.*,
(
SELECT
ROW_TO_JSON(profile)
FROM
(
SELECT
*
FROM
profile p
WHERE
p.account_id = a.id
)
profile
)
AS profile
FROM
account a
WHERE
a.id = 16
这是 JSON 格式的结果
{
"id":16,
"email":"test@gmail.com",
"password":"$password",
"role_id":0,
"created_at":"2020-04-01T22:03:44.324Z",
"profile":{
"id":8,
"username":"firmanjml",
"gender":0,
"bio":null,
"avatar":"www.firmanjml.me/test.jpg",
"account_id":16,
"created_at":"2020-04-02T06:03:44.32498"
}
}
我注意到来自 account 表的父行在 created_at 的末尾有 Z,而转换为 JSON 的子表具有不同的时间戳格式。
有没有办法可以让所有时间戳都采用Javascript 格式?
查询以创建架构和插入数据
CREATE TABLE "account"(
id SERIAL primary key,
email varchar(50) not null,
password varchar(50) not null,
role_id int2 default 0 not null,
created_at timestamp default now() not null
);
CREATE TABLE "profile"(
id SERIAL primary key,
username varchar(50) not null,
gender int2 not null,
bio varchar(50),
avatar varchar(50),
account_id integer not null REFERENCES account (id),
created_at timestamp default now() not null
);
INSERT INTO "account" (email,"password","role_id",created_at) VALUES
('test@gmail.com','$password',0,'2020-04-02 06:03:44.324');
INSERT INTO "profile" (username,gender,bio,avatar,account_id,created_at) VALUES
('fimrnajml',0,NULL,'www.firmanjml.me/test.jpg',1,'2020-04-02 06:03:44.324');
【问题讨论】:
-
根据我的定义,JS 时间戳是错误的。 'Z' 是一个时区,除非你在任何地方都使用它,否则你应该这样标记它。
-
您好,感谢您的回复。如果时间戳带有 Z,我的打字稿模型只能绑定行数据,created_at 的其余部分会给我一个错误。我希望所有时间戳都有“Z”符号。如果没有 Z,它将检测为无效的 DateTime 格式。
标签: javascript node.js postgresql timestamp pg