将对象数组转换为与nodejs/pg/unnest兼容的数组

Convert object array to array compatible for nodejs/pg/unnest

本文关键字:数组 pg unnest nodejs 对象 转换      更新时间:2023-09-26

关于从nodejs/pg中的多个参数更新多行,我需要运行以下命令:

update portfolios p
set votes = s.votes
from unnest(array[(5, 1), (15, 1), (25, 2)]) s (votes int, id int)
where p.id = s.id

其中unnest中的数组为1美元,如下所示:

update portfolios p
set votes = s.votes
from unnest($1) s (votes int, id int)
where p.id = s.id

然而,我的数组最初由对象组成,如:

[{votes: 5, id: 1}, {votes: 15, id: 1}, {votes: 25, id: 2}]

我试着用转换它

my_array = my_array.map(function(e) { return tuple(e.votes, e.id); });

但这失败了。

我需要更正与pg和Client.query.使用的值兼容的数组

如何将我的对象数组转换为尊重javascript和postgresqlunnest?

您可以按原样发送JSON字符串,并让PostgreSQL处理它:

update portfolios p
set votes = s.votes
from (
  select (e->>'votes')::int as votes, (e->>'id')::int as id
  from (select (regexp_replace($1, '"'1"', 'g'))::jsonb as jarr) j
  cross join jsonb_array_elements(jarr) e
  ) s
where p.id = s.id;

其中$1是作为字符串的[{votes: 5, id: 1}, {votes: 15, id: 1}, {votes: 25, id: 2}]', '([a-z]+)

@Ziggy传递JSON的想法是可行的,尽管理想情况是让驱动程序调整您的数组。这是驱动程序必须传递给Postgresql的最后一个查询

update portfolios p
set votes = s.votes
from (
    select (a->>'votes')::int as votes, (a->>'id')::int as id
    from (
        select jsonb_array_elements(a) as a
        from (values ('[{"votes": 5, "id": 1}, {"votes": 15, "id": 1}]'::jsonb)) s(a)
    ) s
) s
where p.id = s.id

以及要传递给驾驶员的查询:

update portfolios p
set votes = s.votes
from (
    select (a->>'votes')::int as votes, (a->>'id')::int as id
    from (
        select jsonb_array_elements(a) as a
        from (values (($1)::jsonb)) s(a)
    ) s
) s
where p.id = s.id

$1参数必须用类似JSON.stringify:的东西来实例化

var a = JSON.stringify(my_array_of_objects);