Node-postgres: Retrieve the inserted row

Created on 22 Oct 2014  路  2Comments  路  Source: brianc/node-postgres

Hi.
According to the documentation (https://github.com/brianc/node-postgres/wiki/FAQ#7-i-just-have-a-question-and-maybe-a-feature-request-that-i-am-not-able-to-think-about-how-to-implement-or-do-it-i-need-to-retrieve-the-inserted-row-or-someway-to-reach-it-after-the-insert-is-done) we can get the row after the insert is done, but the result.rows is empty.

I do

var pg = require('pg');
var connectionString = process.env.DATABASE_URL;
pg.connect(connectionString, function(err, client, done) {
   //error handler
   client.query('INSERT INTO users (uid,name...) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)', [...], function(err, result) {
    //error handler
    console.log(result);
...

And get

{ command: 'INSERT',
  rowCount: 1,
  oid: 0,
  rows: [],
  fields: [],
  _parsers: [],
  RowCtor: null,
  rowAsArray: false }

Most helpful comment

Whoah! I just checked the wiki and there's a subtle problem in crome...that example actually has a horizontal scroll on it but it breaks just perfectly so you don't really know...

image

basically you need to tack on a returning statement at the end of your insert. This functions kinda like doing an insert and a "SELECT * FROM what_i_just_inserted" in the same query.

I'll modify the wiki slightly to hopefully make that query easier to see on one line.

All 2 comments

Whoah! I just checked the wiki and there's a subtle problem in crome...that example actually has a horizontal scroll on it but it breaks just perfectly so you don't really know...

image

basically you need to tack on a returning statement at the end of your insert. This functions kinda like doing an insert and a "SELECT * FROM what_i_just_inserted" in the same query.

I'll modify the wiki slightly to hopefully make that query easier to see on one line.

Thanks, it works now!

Was this page helpful?
0 / 5 - 0 ratings