V
V
Viktor2022-03-21 00:57:45
JavaScript
Viktor, 2022-03-21 00:57:45

node+pg. How to insert multiple rows into a table?

Tell me, I can’t insert many lines from an object into the database.
Server on Node + express, to connect to the database I use pg
Data for example.

const data = [
   { id: 1, status: 'ok', type: 'def',  time: '22:15' },
   { id: 2, status: 'error', type: 'error',  time: '22:15'  },
   { id: 3, status: 'ok', type: 'def',  time: '22:15'  },
]

await pool.query(
  `INSERT INTO public.orders(id, status, type, time) \
  VALUES ($1, $2, $3, $4) RETURNING *`,
  data.map((item) => [item.id, item.status, item.type, item.time])
)


I get an error bind message supplies 3 parameters, but prepared statement "" requires
4 when iterating, it considers each array as a separate parameter, and not as a set of parameters.

Sending requests separately with each line is not an option, there can be several tens of thousands of such lines, and you don’t want to put the server.
How to write a lot of data to the database in one query?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2022-03-21
@VelkinVV

something like this

await pool.query(
  `INSERT INTO public.orders(id, status, type, time) \
  SELECT unnest(array[%1]), unnest(array[%2]), unnest(array[%3]), unnest(array[%4])`,
  [
    data.map(item => item.id),
    data.map(item => item.status),
    data.map(item => item.type),
    data.map(item => item.time),
  ]
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question