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?

1
  • Line if(!db) { does precisely nothing in your code. See verifying connection. Commented Feb 23, 2019 at 12:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That appears to be the problem. Thanks a lot!

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.