How to insert multiple rows into a PostreSQL database using NodeJS

76
January 10, 2020, at 9:50 PM

I'm trying to add multiple rows to my database in ReactJS by using

let request = new Request('http://localhost:3000/songs', {
    method: 'POST',
    headers: new Headers({ 'Content-Type': 'application/json' }),
    body: JSON.stringify(data)
  }); 

Here's what the data array looks like

And in my NodeJS app I'm trying add the objects like this

addSong = (request, response) => {
  const id = parseInt(request.params.id)
  const { name, link } = request.body;
  pool.query('INSERT INTO songs (name, link) VALUES ($1, $2) RETURNING *', [name, link], (error, results) => {
  if (error) {
    throw error
    console.log(error)
  } else {
    console.log(results.rows);
    response.status(201).send(`Songs added` + request.body.name);
  }
 });
}

index.js

const app = express();
const db = require('./queries');
app.post('/songs', db.addSong)

The problem I'm facing is I believe the code in the NodeJS app only can insert one record? How do I make it so that I can add all the objects from the array to make multiple rows? I was told a for loop which sounds right but I don't know how to implement that.

Answer 1

Query :

"INSERT INTO songs (name, link) VALUES ($1, $2) RETURNING *',  [[name1,link1], [name2,link2]];"
Answer 2

I got this to save all the objects to the database by using a for loop:

const addSong = (request, response) => {
  const id = parseInt(request.params.id)
  const { name, link } = request.body;
for (var i = 0; i < request.body.length; i++) {
  pool.query('INSERT INTO songs (name, link) VALUES ($1, $2) RETURNING *', [request.body[i].name, request.body[i].link], (error, results) => {
  if (error) {
    throw error
    console.log(error)
  } else {
    console.log("Rows " + JSON.stringify(results.rows));
  }
 });
 }
}

I iterate through each object in my array and insert each object with name and link.

READ ALSO
How to load a module only if it exists in node/gulp?

How to load a module only if it exists in node/gulp?

I'm trying to correctly configure my Gulp setup, and I want to load moduleA if it exists, or moduleB instead, if moduleA doesn't exists

89
Is Puppeteer-Cluster Stealthy enough to pass bot tests?

Is Puppeteer-Cluster Stealthy enough to pass bot tests?

I wanted to know if anyone using Puppeteer-Cluster could elaborate on how the ClusterLaunch({settings}) protects against sharing of cookies and web data between pages in different context

92
NodeJS | Mongoose not updating value in DB

NodeJS | Mongoose not updating value in DB

In array I'm updating a valueI am setting member approved value to true then I console

73
How to send initial data on page load?

How to send initial data on page load?

I have a Single Page Application with a server that serves the indexhtml on the / route

68