I'm trying to SELECT data from a Postgresql database, using Node.js. I have been able to return the result, but I'm having trouble accessing the contents of the result. My query code looks like this:
select: function(selection, table, condition, limit,callback)
{
pool.connect(function(err, client, done)
{
let sql;
let rows = [];
if(selection === 'ALL')
{
sql = 'SELECT * FROM ' + table + ' WHERE ' + condition;
}
else
{
sql = 'SELECT ' + selection + ' FROM ' + table + ' WHERE ' + condition;
}
if(isDefined(limit))
{
sql = sql + ' LIMIT ' + limit;
}
if (err)
{
return console.error('Error acquiring client', err.stack);
}
if (sql === '')
{
console.log("Error: No SQL statement!");
}
else
{
console.log("Running query \'" + sql + "\'.");
client.query(sql,
function(err, result)
{
if (err)
{
console.log('Query error: ' + err);
}
else
{
rows = result.rows;
callback(rows);
}
});
}
});
},
The callback passes "rows". The code where this is picked up looks like this:
let selection = 'prefname';
let table = 'users';
let condition = `fbid='${senderID}'`;
let limit = 1;
let dbData = [];
let rowString;
let greetingText;
userData.FBUser = uName;
db.select(selection,table,condition,limit, function(res)
{
dbData = res;
if (!isDefined(dbData))
{
console.log("Nothing returned!");
}
else
{
rowString = JSON.stringify(dbData);
console.log("Returned: " + rowString);
for (let key in rowString)
{
if (rowString.hasOwnProperty("prefname"))
{
console.log("TRUE");
}
}
}
}
);
Now, when I run this code, I can see that SOMETHING has been returned from my database. In my console log, I see this:
2018-01-25T17:57:09.465642+00:00 app[web.1]: Running query 'SELECT prefname FROM users WHERE fbid='1769596366406807' LIMIT 1'.
2018-01-25T17:57:09.470727+00:00 app[web.1]: Returned: [{"prefname":"Sam"}]
So I know SOMETHING has been returned, but for some reason I cannot get into the JSON string to pull it out. I've tried using for...in, but it hasn't worked.
Is there a better way to do what I'm trying to do? Am I even doing it right at all?