2

I run select query using pg ,node.js and hapi, and its work.
but how can i return the rows?

The selected:

 var client = new pg.Client(conString);
        client.connect(function(err,done) {

            if (err) {
                return console.error('could not connect to postgres', err);
            }
        })


function fun(query){
 client.query(query, function (err, result,done) {
                if (err) {
                    console.error('error running query', err);
                    return;
                }
                else{

                    result.rowAsArray=true;
                    console.log(result.rows[0]);
                    data=result.rows;
            }

            });
            return data

        }
}

but its return a object with nothing,
What is the right way?
Thank you.

1 Answer 1

1

You need to loop through the result set.

function fun(query) {
  var data = [];

  var sql = client.query(query, function(err, result) {
    if (err) {
      console.error('error running query', err);
      return;
    }
  });

  sql.on('row', function(row) {
    console.log(row);
    data.push(row);
  }

  return data;
}
Sign up to request clarification or add additional context in comments.

7 Comments

i get this error: TypeError: Object [object Object] has no method 'on'. what can i do?
I corrected the answer. The on row event handler should have been outside of the query function. But, in fact your approach was good. You should be able to assign data=result.rows and then return data. What is the value of result.rowCount?
The error now is: TypeError: Uncaught error: Object select * from sponsors has no method 'on' where does on() come from?
The value of rowCount is 8
Try now, the name of the variable was conflicting with the name of the function argument - query.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.