简体   繁体   English

Node JS:在postgres查询后选择json数据

[英]Node JS : Select json data after postgres query

I am trying to get some Data from my postgres Database. 我试图从我的postgres数据库中获取一些数据。 But when I try to get the json data from the postgres result, I always receive an error. 但是,当我尝试从postgres结果获取json数据时,我总是会收到错误消息。

Here is my Node JS code: 这是我的Node JS代码:

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" umschlagInnen.sourceUserID为“ 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? 你能找到我的任何错误吗?

First, there is an error on the capitalisation of your pubKey variable: 首先,您的pubKey变量的大小写有误:

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. 但请记住,该console.log()将在查询回调函数执行之前执行,因此pubKey仍然无效。 Move the console.log() inside the callback function and it should contain your data. 将console.log()移到回调函数中,它应该包含您的数据。

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 ...
  });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM