2016-09-30 103 views
0

我試圖讓pg-promise在NodeJS中工作以允許我連接到PostgreSQL數據庫。 node和postgre都在運行Ubuntu的codeanywhere節點框中運行。無法在NodeJS中使用pg-promise查詢PostgreSQL數據庫 - 「關係不存在」

下面是相關代碼:

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

運行node bot.js打印以下內容:

{ [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' } 

,並打印以下到/var/log/postgresql/postgresql-9.3-main.log

2016-09-29 23:09:29 EDT ERROR: relation "users" does not exist at character 15 

我做了什麼錯?我想這應該是與db.any(),如下面的代碼不工作:

//db.any("select * from users") 
db.connect() 
    .then(function (data) { 
     console.log(data); 
    }) 
    .catch(function (error) { 
     console.log(error); 
    }); 

輸出是一些看起來大約類似於db對象返回,但是這不是我所需要的..

我已經看到其他提到大寫作爲一個問題的stackoverflow問題。具體來說,他們說postgresql會使你的輸入全部小寫,而不用雙引號。要解除任何這樣的相關概念:

postgres=# \dt                        
     List of relations                     
Schema | Name | Type | Owner                   
--------+-------+-------+----------                   
public | users | table | postgres                   
(1 row) 

這種關係肯定存在。

我缺少什麼?

回答

1

錯誤是告訴你在你的數據庫中沒有users表。您需要先創建表格,然後才能從中進行選擇。請記住,表名是區分大小寫的,所以如果您創建了Users表,您的查詢將不起作用。

CREATE TABLE Users (...); 
SELECT * FROM users; -- this will cause an error 

你應該嘗試使用psql -d users連接到數據庫(在這種情況下users是你的數據庫,而不是與你同名的表混淆的名稱)在命令行上。從那裏你可以編寫查詢來獨立於應用程序代碼測試它們。如果在連接到users數據庫時遇到問題,可以使用psql連接到默認數據庫,並輸入\l\list來列出postgres知道的所有數據庫。

要注意在Postgres本身有一個內置的名爲postgres數據庫都有自己的users表來管理訪問控制的其他數據庫。您可以通過查看命令提示符來確定您在psql中連接了哪個數據庫;如果它表示postgres=,那麼你在postgres數據庫中,而不是你自己的。

+0

見編輯;表名爲'users' – Menasheh

+0

你列出的是'postgres'數據庫中的用戶表,而不是你的數據庫(你也命名爲'users')。因爲'postgres ='提示符,你可以告訴你在postgres數據庫中。 – Soviut

+0

感嘆...所以它自動被稱爲postgres,因爲這就是用戶名是什麼? – Menasheh