Search code examples
node.jspostgresqlexpresspg

How to properly query Postgresql database using pg with Node.js?


I am attempting to query a Postgresql database using Node, Express, and the pg module. I am getting the error "TypeError: Cannot read property 'query' of undefined"

I have looked at the node-postgres module website for the correct syntax as well as various other websites. I know that the syntax used to enable pg changed after pg version 6.3.0.

const express = require("express");
const path = require("path");
const bodyparser = require("body-parser");
const consolidate = require("consolidate");
const dust = require("dustjs-helpers");
const pg = require("pg");
var pool = new pg.Pool();


let app = express();

let connect = "postgres://postgres:secret@localhost:5432/my_database";

app.engine("dust", consolidate.dust);

app.set("view engine", "dust");
app.set("views", __dirname + "/views");

app.use(express.static(path.join(__dirname, "public")));

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

app.get("/", function(request, response, next) {
    pool.connect(function(err, client, done) {
      if (err) {
        console.log(`Not able to get a connection: ${err}.`);
        response.status(400).send(err);
      }
      client.query("SELECT * FROM recipes", function(err, result) {
        done();
      });
      pool.end();

    });
});

app.listen(3000, () => {
    console.log("Server running on port: 3000");
});

Going to http://server_ip:3000 should show a webpage instead node crashes with this error:

client.query("SELECT * FROM recipes", function(err, result) {
             ^
TypeError: Cannot read property 'query' of undefined

Solution

  • You need to pass your connection string to pool when you instantiate it.

    var pool = new pg.Pool({
        connectionString: 'postgres://postgres:secret@localhost:5432/my_database',
    });