Reputation: 479
Got a shortcoming of brain.exe for some reason currently.
I am using Node.js and node-postgres to query my DB.
I am trying to insert an array of text, basically, into a PostgreSQL column.
logging the array with JSON.stringify() looks like this:
["id1","id2","id3"]
Will I just be able to
'INSERT INTO table (array) VALUES ($1)' [data]'
?
(extremely simplified - The data array is variable in length)
Upvotes: 1
Views: 4263
Reputation: 102257
Here is the solution:
import { pgclient } from '../../db';
(async function test() {
try {
await pgclient.connect();
// create table
await pgclient.query(`
CREATE TABLE IF NOT EXISTS my_table (
id serial PRIMARY KEY,
arr varchar[]
)
`);
// test
const array = ['id1', 'id2', 'id3'];
await pgclient.query(`INSERT INTO my_table (arr) VALUES ($1)`, [array]);
} catch (error) {
console.log(error);
} finally {
pgclient.end();
}
})();
After executed above code, check the database:
node-sequelize-examples=# select * from "my_table";
id | arr
----+---------------
1 | {id1,id2,id3}
(1 row)
Upvotes: 3