ELD
ELD

Reputation: 338

How to do insert with array in SQL with JavaScript Node?

i have a problem. I have an array and i want that each element to be a row from column;

Example:

My Array: const myArray = ['A', 'B', 'C', 'D'];

and result is:

Column1 | 
-----------------------------------------
    A   |  
    B   |  
    C   |  
    D   |  

I am using Node.js with library node-postgres:

var queryString = "INSERT INTO test (id) VALUES (" + "'" + [myArray] + "'" + ") RETURNING *";

pool.connect((err, client, done) => {
  if (err) {
    done();
    console.log(err)
    return res.status(500).json({
      success: false,
      data: err
    })
  }
  client.query(queryString, (err, result) => {
    done();
  });
})

But it goes like a bigger string;

Someone could help me?

Upvotes: 0

Views: 3572

Answers (2)

ic3b3rg
ic3b3rg

Reputation: 14927

I think this is what you're looking for:

var queryString = `INSERT INTO test (id) VALUES ("${myArray.join('"),("')}") RETURNING *`

i.e.

INSERT INTO test (id) VALUES (("A"),("B"),("C"),("D")) RETURNING *

A better solution would be to use query parameters:

var queryString = `INSERT INTO test (id) VALUES (${myArray.map((v,i) => `$${i+1}`).join('),(')}) RETURNING *`

i.e.

INSERT INTO test (id) VALUES (($1),($2),($3),($4)) RETURNING *

And then use it like:

client.query(queryString, myArray, (err, result) => {
  done();
});

Upvotes: 2

ALMEK
ALMEK

Reputation: 194

Well! I am sure this should have been asked somewhere. but whatever.. ..you should have a code look like the following. - by simply add multiple inserted values as nested array. :

    var queryString = "INSERT INTO test (id) VALUES ($1) RETURNING *";
    var values = [['A'],['B'],['C'],['D']]

and when you come to the client query

   client.query(queryString, values, (err, result) => ...

Upvotes: 0

Related Questions