0

I have a PostgreSQL database hosted on Heroku. Here is how I connect to it:

//sql_conn.js
const pgp = require('pg-promise')();
pgp.pg.defaults.ssl = true;

const db = pgp('postgres://connection_string_redacted');

if(!db) {
    console.log("Database setup unsuccessful.");
    process.exit(1);
}

module.exports = db;

And I try to access it here:

//test-endpoint.js
const express = require('express');
const app = express();
const router = express.Router();
let db = require('../utils/sql_conn').db;
const bp = require('body-parser');
router.use(bp.json());

router.get("/", (req, res) => {
    let query = "SELECT * FROM table;";
    db.manyOrNone(query)
        .then((rows) => {
            res.send({
                success: true,
                result: rows
            })
        }).catch((err) => {
            res.send({
                success: false,
                error: err
            })
        });
});

module.exports = router;

I have verified that the connection string is correct, the database is live on Heroku, and the path of the require statement is correct, but calling test-endpoint.js from the browser returns:

TypeError: Cannot read property 'manyOrNone' of undefined

Why is the database undefined?

Foxy
  • 21
  • 2
  • Line `if(!db) {` does precisely nothing in your code. See [verifying connection](https://stackoverflow.com/questions/36120435/verify-database-connection-with-pg-promise-when-starting-an-app). – vitaly-t Feb 23 '19 at 12:45

1 Answers1

1

It looks like an import/export problem. Try to replace this line:

let db = require('../utils/sql_conn').db;

by

const db = require('../utils/sql_conn');

And you should be fine.

mathieux51
  • 344
  • 4
  • 10