2

I have an existing postgresql database with Rails, now I'm making a Node.js app which is using the same database. I already have users in my db and now I would like to list them all.

I successfully created an express app and then I did as follows:

✗ npm install --save sequelize pg pg-hstore
✗ sequelize init

index.js

const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const pg = require('pg');
var conString = 'postgres://localhost:5432/db_name';
var client = new pg.Client(conString);
const app = express();

client.connect(err => {
  if (err) {
    console.error('connection error', err.stack);
  } else {
    console.log('connected');
  }
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', (req, res) => {
    res.send(models.User.findAll);
});

const PORT = process.env.PORT || 5000;
app.listen(PORT);

In my config.json I have:

"development": {
"username": "my_username",
"password": null,
"database": "database_name",
"host": "127.0.0.1",
"dialect": "postgres"
}

I get this error: UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

I'm probably missing a big step but I don't know what it is, I have never done this before.

3
  • Lets try to catch the error first by adding then and catch block to client.connect() Commented Apr 4, 2018 at 6:26
  • I changed the code a little bit, I get the message connected. Still trying to figure out how to do the queries Commented Apr 4, 2018 at 6:35
  • I answered with a table creation query. Commented Apr 4, 2018 at 7:00

2 Answers 2

2

Example Query

const query = {
     text: 'CREATE TABLE IF NOT EXISTS coverages ('+
                'vaccine VARCHAR(64),' +
                'country VARCHAR(255),' +
                'region VARCHAR(255),' +
                'year VARCHAR(4),' +
                'value VARCHAR(12),' +
                'PRIMARY KEY(vaccine, country, region, year, value))'
};
client.query(query)
.then(function(res) {
    console.log(res);
})
.catch(function(err) {
    console.log('\nError executing query', err.stack);
});
Sign up to request clarification or add additional context in comments.

2 Comments

How do I render this on the screen (not in the console)?
Do your query inside app.get function and then response with the result.
1

Here are some example queries using async / await (which requires Node 8+, I believe, so make sure your version supports this):

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

var router = express.Router();

let conString = 'postgres://localhost:5432/db_name';

var postgrespool = new pg.Pool({
  connectionString: conString
});

router.get('/checkdbconnection', function(req, res, next) {
  (async () => {

    // Here is the query!
    // alter it to query a table in your db
    // this example just confirms a connection
    var { rows } = await postgrespool.query(`
      SELECT 
        'Hello from Postgres' AS pg_val;`);

    if (rows.length) {
      return res.send(rows);
    } else {
      res.status(404);
      return res.send('No response from database.');
    }
  })().catch(e =>
    setImmediate(() => {
      res.status(500);
      console.log(e);
      return res.send('Error: ' + e.message);
    })
  );
});

router.get('/checkdbconnection/:name', function(req, res, next) {
  let param_name = req.params.name;

  (async () => {

    // this example demonstrates how to pass parameters to your query with $1, $2, etc.
    // usually, the cast of "::text" won't be necessary after the "$1"
    var { rows } = await postgrespool.query(`
      SELECT 
        'Hello from Postgres' AS pg_val,
        $1::text AS parameter;`, [param_name]);

    if (rows.length) {
      return res.send(rows);
    } else {
      res.status(404);
      return res.send('No response from database.');
    }
  })().catch(e =>
    setImmediate(() => {
      res.status(500);
      console.log(e);
      return res.send('Error: ' + e.message);
    })
  );
});

module.exports = router;

If you visit http://localhost:5000/checkdbconnection , you'll get this response:

[
  {
    "pg_val": "Hello from Postgres"
  }
]

And if you visit, say, http://localhost:5000/checkdbconnection/Al-josh , you'll get this:

[
  {
    "pg_val": "Hello from Postgres",
    "parameter": "Al-josh"
  }
]

Hopefully my comments in the code have made it clear how the queries work, so you can alter them to your purpose. If not, provide some more detail about your tables and I can amend this answer.

Note also that I am using pg.Pool here to connect to Postgres. This is totally secondary to your question, but the documentation is worth reading.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.