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

关于从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 

我的数组是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和postgresql unnest?

你可以发送你的JSONstring,并让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}]', '([az]+)

@Ziggy想法通过JSON可以工作,但理想的是让驱动程序适应你的arrays。 这是驱动程序必须传递给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);