因此,当我使用:node app.js user2
运行应用程序时,我会得到一个我不想要的SQL格式响应。我的另一个问题是,当我尝试检查"user2"是否为Admin时,它会说它甚至不在我的数据库中。。。
我希望它记录:
user2 is admin
Admins: user2
这是我一直得到的。。。
我不想登录:
user2 is not admin
Result {
command: 'SELECT',
rowCount: 1,
oid: null,
rows: [ { username: 'user2' } ],
fields:
[ Field {
name: 'username',
tableID: 16398,
columnID: 2,
dataTypeID: 25,
dataTypeSize: -1,
dataTypeModifier: -1,
format: 'text' } ],
_parsers: [ [Function: noParse] ],
_types:
TypeOverrides {
_types:
{ getTypeParser: [Function: getTypeParser],
setTypeParser: [Function: setTypeParser],
arrayParser: [Object],
builtins: [Object] },
text: {},
binary: {} },
RowCtor: null,
rowAsArray: false }
我的代码是…
const net = require('net');
const fs = require('fs');
const request = require('request');
const pg = require('pg');
const conString = 'postgres://user_1:test123@localhost:5432/websocks';
const client = new pg.Client(conString);
client.connect();
const username = client.query('SELECT username FROM websocks.users');
const userData = client.query('SELECT id, username, password, rank FROM websocks.users');
const isAdmin = client.query('SELECT username FROM websocks.users where rank = 1');
isAdmin.then(function(result) {
if (process.argv[2] === result) {
console.log(process.argv[2] + ' is admin!');
} else {
console.log(process.argv[2] + ' is not admin');
}
console.log("Admins: " + result);
});
如果我很了解,您的第一个问题是如何从client.query中检索数据。例如,对于这个查询,const userData = client.query('SELECT id, username, password, rank FROM websocks.users');
postgres将返回一个数组(PG节点库在对象数组中转换的结果集列表(。你已经有了结果。您必须以这种方式从结果中检索"行"属性:
userData.then(result => {
const usersDataArray = result.rows ;
usersDataArray.foreach (row => {
console.log (row.id);
console.log (row.username);
console.log (row.password);
});
});
第二个问题也是如此。ClientQuery返回一个包含查询实际结果的包装对象
若要检索实际结果,必须访问此对象的rows属性。这应该有效:
isAdmin.then(function(result) {
//i suppose that user with the rank 1 are admin so if the query return at least one result, that mean there is an admin in the database
if ( result.rows.length > 0 ) {
console.log(result.rows[0].username + ' is admin!');
} else {
console.log(process.argv[2] + ' is not admin');
}
console.log("Admins: " );
console.log( result.rows);
});