How to bind array to IN condition with Node postgres

Viewed 1013

I'm struggling to figure out of to bind an array to an IN query in node pg library.

  const env = 'foo';
  const sourceTypes = ['one', 'two'];

  const resp = await pool.query(
    `SELECT source_id, target_id FROM records
    WHERE target_env = $1
    AND source_type IN ($2)`,
    [env, sourceTypes],
  );

I've tried several variations and they either error out or don't return any data.

I can make the query when I just use when I manually bind to generate something like this:

SELECT source_id, target_id FROM records
    WHERE target_env = 'foo'
    AND source_type IN ('one', 'two')

PS: If can provide suggestion on how to actually see the SQL request that PG is generating, that would be extremely helpful!

1 Answers

You can't bind an array to multiple elements of a list in one go. But you can use an array instead of a list by changing in ($2) to =ANY($2)

You can see what queries are getting sent by setting log_statement=all and then viewing the PostgreSQL log file.

Related