Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I am trying to get some Data from my postgres Database. But when I try to get the json data from the postgres result, I always receive an error.

Here is my Node JS code:

pg.connect(connectionString, function(err, client, done) {
var pubKey;
var query1 = client.query("SELECT * FROM users where userid=($1) ORDER BY userid ASC;", [umschlagInnen.sourceUserID]);

    query1.on('row', function(row) {
        pubKey = row;
    });

    console.log(pubkey.pubkey);
}

umschlagInnen.sourceUserID is "2"

My postures-table for "users" looks like this:

users(userID int PRIMARY KEY, saltMaster varchar(255) not null, privKeyEnc varchar(2048) not null, pubKey VARCHAR(2048) not null)

The error:

ReferenceError: pubkey is not defined

Can you find any of my Mistakes?

share|improve this question
up vote 0 down vote accepted

First, there is an error on the capitalisation of your pubKey variable:

pg.connect(connectionString, function(err, client, done) {
  var pubKey;
  var query1 = client.query("SELECT * FROM users where userid=($1) ORDER BY userid ASC;", [umschlagInnen.sourceUserID]);

  query1.on('row', function(row) {
    pubKey = row;
  });

  console.log(pubkey.pubkey); // broken version
  console.log(pubKey.pubKey); // fixed version
}

but bear in mind that this console.log() will be executed before the query callback function executes, so pubKey is still not valid. Move the console.log() inside the callback function and it should contain your data.

Try this:

pg.connect(connectionString, function(err, client, done) {
  // var pubKey; <-- don't need this variable anymore
  var query1 = client.query("SELECT * FROM users where userid=($1) ORDER BY userid ASC;", [umschlagInnen.sourceUserID]);

  query1.on('row', function(row) {
    console.log(row.pubKey);
    // do something with the data here ...
  });

}
share|improve this answer
    
Thank you very much @Gavin Gregory. That helped me a lot and fixed my problem. – bobafett1 Jun 27 at 20:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.