Search code examples
javascriptnode.jspostgresqlnode-postgres

node-postgres: Update more than one record at once


I'm building an app in node.js using node-postgres. I don't know how to update more than one record at once.
Here is my code:

var status = 20;
var id = [23,12,43];

pool.connect(function(err, client, done) 

{


if(err) 
{
      done();
      console.log(err);
      return res.status(500).send(json({ success: false, data: err}));
}
    client.query("UPDATE myDatabase SET status=($1) WHERE id IN($2);", [status,id]);

But I've got a problem - console:

events.js:160 throw er; // Unhandled 'error' event ^

error: invalid input syntax for integer: "23,12,43"

What can I do in that case? What kind of data use? the length of var id will be not the same every time.

Greetings, Rafał
EDIT: I think that a change of data will work in javascript, the input must be 23,12,43, but instead is [23,12,43] but I don't know how to make that.


Solution

  • It looks like you want to use ANY:

    client.query("UPDATE myDatabase SET status=($1) WHERE id = ANY($2);", [status,id]);
    

    This is due Postgresql itself, not the library: see this and this

    See also this question: Oracle: '= ANY()' vs. 'IN ()'