I'm trying to get pg-promise working in NodeJS to allow me to connect to my PostgreSQL database. Both node and postgre are running in a codeanywhere node box running Ubuntu.
Here's the relevant code:
var pgp = require('pg-promise')();
var bot = new TelegramBot(token, { polling: true });
var db = pgp({
host: 'localhost',
port: 5432,
database: 'users',
user: 'postgres',
password: '(pass here)'
});
db.any("select * from users")
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log(error);
});
Running node bot.js
prints the following:
{ [error: relation "users" does not exist]
name: 'error',
length: 96,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '15',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '984',
routine: 'parserOpenTable' }
And prints the following to /var/log/postgresql/postgresql-9.3-main.log
:
2016-09-29 23:09:29 EDT ERROR: relation "users" does not exist at character 15
What did I do wrong? I guess it should be something with db.any(), as the following code does work:
//db.any("select * from users")
db.connect()
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log(error);
});
The output is a return of something that looks approximately like the db
object, but that's not what I need...
I've seen other stackoverflow questions mentioning capitalization as an issue. Specifically, they say that postgresql will make your input all lowercase without double quotes. To dispell any such notion of relevance:
postgres=# \dt
List of relations
Schema | Name | Type | Owner
--------+-------+-------+----------
public | users | table | postgres
(1 row)
The relation certainly does exist.
What am I missing?
The error is telling you that there is no
users
table in your database. You need to create the table before you can select from it. Remember, the table name is case sensitive so if you created aUsers
table, your query won't work.You should try connecting to your database using
psql -d users
(users
in this case is the name of your database, not to be confused with your table of the same name) on the command line. From there you can write queries to test them independently from your application code. In case you're having trouble connecting to yourusers
database, you can always connect to the default database with psql and type\l
or\list
to list all databases postgres knows about.Note that Postgres itself has a built in database named
postgres
that has its ownusers
table to manage access control to other databases. You can tell which database you're connected to in psql by looking at the command prompt; If it sayspostgres=
then you're in the postgres database, not your own.