I want to get the inserted ID from INSERT query. But response always empty array. How to get the inserted ID.
const client= new Client({
host: "host",
user: "me",
password: `myPassword`,
database: "test",
port: 5432
});
client.connect();
client.query(query, data, (err, res) => {
client.end();
if (err) return reject(err);
return resolve(res);
});
Insert query returns following response
{
"command": "INSERT",
"rowCount": 1,
"oid": 0,
"rows": [],
"fields": [],
"_parsers": [],
"RowCtor": null,
"rowAsArray": false
}
You’ll need to use INSERT’s RETURNING clause. The documentation is at https://www.postgresql.org/docs/current/static/sql-insert.html and it looks like this:
INSERT INTO a_table (column1, …) VALUES (value1, …) RETURNING id_column
Most helpful comment
You’ll need to use
INSERT’sRETURNINGclause. The documentation is at https://www.postgresql.org/docs/current/static/sql-insert.html and it looks like this: