Alfred Balle
Alfred Balle

Reputation: 1195

NodeJS, pg-promise and array as parameter

Running NodeJS and pg-promise.

I've got an array:

let my_array = new array('x', 'y', 'z');

I'm trying to pass this as a parameter to my PostgreSQL query with pg-promise:

db_webhooks.any('SELECT cars FROM my_cars WHERE id IN ($1)', [my_array])
  .then...

But it fails with type error. I've tried to .join the array, but also get error, as it result in a string 'x,y,z' instead of 'x','y','z'.

Printing out the debug/query called gives me:

QUERY: SELECT cars FROM my_cars WHERE id IN (array['x','y','z'])

This should be:

QUERY: SELECT cars FROM my_cars WHERE id IN ('x','y','z')

Upvotes: 4

Views: 1761

Answers (1)

vitaly-t
vitaly-t

Reputation: 25840

The library supports CSV Filter for this purpose:

await db.any('SELECT cars FROM my_cars WHERE id IN ($1:csv)', [my_array])
/*=> SELECT cars FROM my_cars WHERE id IN ('x', 'y', 'z') */

or you can use :list, which is the same:

await db.any('SELECT cars FROM my_cars WHERE id IN ($1:list)', [my_array])
/*=> SELECT cars FROM my_cars WHERE id IN ('x', 'y', 'z') */

Upvotes: 5

Related Questions