Ahmet Hakan Billur
Ahmet Hakan Billur

Reputation: 103

Get data from database with node.js

I start node.js with simple node example.

My simple project provide that to get data(select * from bla bla bla) from db but i have a problem is as follows:

Error: No such database: hakan_billur
    at Connection.parseE (C:\Users\hakan_billur\workspace\postgre-bilgi2\node_modules\pg\lib\connection.js:539:11)
    at Connection.parseMessage (C:\Users\hakan_billur\workspace\postgre-bilgi2\node_modules\pg\lib\connection.js:366:17)
    at Socket.<anonymous> (C:\Users\hakan_billur\workspace\postgre-bilgi2\node_modules\pg\lib\connection.js:105:22)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
    at TCP.onread (net.js:538:20)
Program node ./bin/www exited with code 1

database.js is as follows:

var pg = require('pg');
var path = require('path');
var connectionString = require(path.join(__dirname, '../', '../', 'config'));

config.js is as follows:

var connectionString = process.env.DATABASE_URL || 'postgres://portal:por**[email protected]:6432';

module.exports = connectionString;

index.js is as follows:

var express = require('express');

var router = express.Router();

var path = require('path');
var pg = require('pg');

var connectionString = require(path.join(__dirname, '../', '../', 'config'));

router.get('/', function(req, res, next) {
var results = [];

var client = new pg.Client(connectionString);
client.connect();

// Get a Postgres client from the connection pool
pg.connect(connectionString, function(err, client, done) {

// SQL Query > Insert Data
var query = client.query("SELECT * FROM poll where is_active=true");

query.on('row', function(row) {
    results.push(row);
});

console.log(results);

// After all data is returned, close connection and return results
query.on('end', function() {
    client.end();
    console.log(results);
    return res.json(results);
});

// Handle Errors
if(err) {
  console.log(err);
}
});

res.sendFile(res.render(path.join(__dirname, '../', '../', './client', 'views', 'index')));

});

and finally file hierarchy are as follows:

enter image description here

who can help me.Thank you in advance for your help.

Upvotes: 0

Views: 3758

Answers (1)

vitaly-t
vitaly-t

Reputation: 25940

You are missing the database name in your connection string.

The string syntax is as follows:

var cn = "postgres://username:password@host:port/database";

Alternatively, you can use an object:

var cn = {
    host: 'localhost', // server name or IP address;
    port: 5432,
    database: 'my_db_name',
    user: 'user_name',
    password: 'user_password'
};

pg module can automatically understand which one is being used.

P.S. For a good start with PosgreSQL and Node JS check out pg-promise ;)

Upvotes: 2

Related Questions