【发布时间】:2019-10-02 16:34:29
【问题描述】:
我是 NodeJs 的新手,并尝试使用 pg-promise 对我的 PG 数据库执行所有请求。 我希望能够动态更新列,这意味着有时我只会更新一行的两列,有时我会更新所有列,等等...... 我的输入将是 JSON。
因为我希望端点能够更新多行,所以我尝试使用带有 ColumnSet 的 helpers 命名空间。
这是我的 Javascript 代码(灵感来自之前的 stackoverflow 答案):
/* logic for skipping columns: */
const skip = c => !c.exists || c.value === undefined;
/* all the columns of the table */
const column_structure = new dbconfig.pgp.helpers.ColumnSet(
[ '?id',
{name: 'firstname', skip},
{name: 'surname', skip},
{name: 'yob', skip}, // year of birth
{name: 'defensive_skill', skip},
{name: 'offensive_skill', skip},
{name: 'login', skip},
{name: 'password', skip}
],
{table: 'players'});
这是我提供给端点的 JSON:
[{
"id" : 25,
"firstname": "Stephen",
"surname": "Harrison",
"yob": 1991,
"defensive_skill": 5,
"offensive_skill": 3,
"login": "harry",
"password": "123456"
},
{
"id": 26,
"firstname": "Chris",
"surname": "Jackson",
"defensive_skill": 5,
"offensive_skill": 4,
"login": "chris",
"password": "123456"
}
]
这是错误:
Property 'yob' doesn't exist.
如您所见,在我的数组的第二个对象中,我没有指定字段“yob”。 我期待对于第二个对象,除了“yob”之外的所有列都将被更新。 是不是我做错了什么?
【问题讨论】:
-
你是插入一个有列的表还是只是一个 json/jsonb 的列?大概如果这是一个表关系,它会告诉您
yob列不存在,需要添加。 -
@Lucas 总共有八列,更新时我希望能够单独更新每一列。没有“json/jsonb 列”。我认为我的问题与“pg-promise”有关。
-
更正了 skipCB 类型的无效使用,从
c => !c.exists || c === undefined;到c => !c.exists || c.value === undefined;。
标签: javascript node.js postgresql express pg-promise