ahmadalibin
ahmadalibin

Reputation: 141

Insert array as column in Node.js

I want to insert each element from an array as the rows of a column.

Example:

array = [1,2,3,2];

the result will be:

column1 | 
---------
    1   |  
    2   |  
    3   |  
    2   |  

I tried out the following code below in my Node.js file but it doesn't seem to work.

var array = [1,2,3,2]; 

var queryString = "INSERT INTO table (column1) VALUES ((${array.map((v,i) => `${i+1}`).join(',')}) RETURNING *";

    db.query(queryString, array, (err, result) => {
        if (err) throw err;
    });

Upvotes: 0

Views: 1432

Answers (1)

Diego
Diego

Reputation: 816

I would rather use a package like sqlstring to ease the query creation and prevent nasty SQL injections. In any case the resulting SQL query should look like;

INSERT INTO table (column1) VALUES (1), (2), (3), (2);

const numbers = [1, 2, 3, 2];
const values = numbers.map (x => `(${x})`).join (', ');
const query = `INSERT INTO table (column1) VALUES ${values};`;

Upvotes: 1

Related Questions