Search code examples
node.jsarrayspostgresqlsql-insertnode-postgres

NodeJS–Add Array of String in PostgreSQL Query


I am trying to write a postgres query (executed in nodejs using a pool created using the node-postgres package) that will insert a new row in a table. One of the columns in this table is of type text[]. My code is as follows:

pool.query('INSERT INTO paragraphs (lines) VALUES (ARRAY[$1]::TEXT[]) RETURNING id', [my_array], (err, results) => {
            if (err) {
              reject(err)
              return;
            }
            
            resolve(results.rows[0].id)
})

paragraphs is the name of my table and lines is the name of the column of type text[]. my_array is a list of strings. My problem is that what is inserted is not an array of strings, but rather a single string formatted like an array. e.x.:

{"[\"First line\", \"Second line\", \"Third Line\"]"}

I want it to be:

{"First line", "Second line", "Third Line"}

I have also tried taking out the ARRAY and TEXT parts (so the sql looks like INSERT INTO paragraphs (lines) VALUES ($1) RETURNING id in the above query), but then I receive the errors:

malformed array literal: "["New First line", "Second line", "Third Line"]"
DETAIL:  "[" must introduce explicitly-specified array dimensions.

What is the correct way to insert lists of strings into PostgreSQL tables in nodejs through a query executed by a pool?


Solution

  • According to: https://node-postgres.com/features/queries#parameterized-query

    Parameters passed as the second argument to query() will be converted to raw data types using the following rules: ...

    Array

    Converted to a string that describes a Postgres array. Each array item is recursively converted using the rules described here.

    So:

    VALUES ($1) or VALUES ($1::TEXT[])should suffice.