postgresql:无法调用方法'查询'未定义的

时间:2016-03-03 07:26:59

标签: node.js postgresql

我在一个文件中定义连接,并尝试在另一个文件中访问该连接,此时我收到此错误。

无法调用方法'查询'未定义的

config.js:

var config = require('../config');
var client = config.C;

var query = client.query('CREATE TABLE items(id SERIAL PRIMARY KEY, text VARCHAR(40) not null, complete BOOLEAN)');
query.on('end', function() { client.end(); });

db.js:

list.indexOf("greetings");

为什么会显示错误。如何定义共同连接以及从其他文件访问。

2 个答案:

答案 0 :(得分:0)

我认为您的 config.js 文件存在问题。您将C分配给client.connect(),返回无效。

您应该定义如下

<强> config.js

var pg = require('pg');
var conString = "pg://postgres:*****@localhost:5432/test";
var client = new pg.Client(conString);

module.exports = {
  C : client
};

<强> db.js

var config = require('../config');
var client = config.C;

client.connect(function(err){
    if(err) {
        return console.error('could not connect to postgres', err);
    }
    var query = client.query('CREATE TABLE items(id SERIAL PRIMARY KEY, text     VARCHAR(40) not null, complete BOOLEAN)');
    query.on('end', function() { client.end(); }); 
});

答案 1 :(得分:0)

我得到了答案:

config.js:

var pg = require('pg');
var conString = "pg://postgres:****@localhost:5432/test";
var client = new pg.Client(conString);
client.connect();
module.exports = client;

db.js:

var client = require('../config.js');
var query = client.query('CREATE TABLE test1(id SERIAL PRIMARY KEY, text VARCHAR(40) not null, complete BOOLEAN)');
  query.on('end', function() { client.end(); });

客户端在这里不会为null。将连接数据库并创建表