Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

700
Views
Connect AWS RDS with Node JS error: Cannot read property 'query' of undefined

I was trying to connect AWS RDS with my Node JS application. I have tested connection of RDS with MySQLWorkbench and the data could be fetched. However when trying to get a connection in my Node application, I got an error:

TypeError: Cannot read property 'query' of undefined

My Node JS code is as follows:

const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
const SELECT_ALL_QUERY = 'SELECT * FROM `my-schema`.`my-table`;';

app.use(cors());

app.get('/', (req, res) => {
    res.send('go to /my-table to see contents')
});

const pool = mysql.createPool({
    connectionLimit: 10,
    host: "process.env.myHostname",
    user: 'process.env.myUsername',
    password: 'process.env.myPassword',
    port: "process.env.3306",
    database: 'my-schema',
    debug: false
});

pool.getConnection((err, connection) => {
    app.get('/my-table', (req, res) => {
        console.log(connection);
        connection.query(SELECT_ALL_QUERY, (err, results) => {
            if (err) {
                return res.send(err)
            }
            else {
                return res.json({
                    data: results
                })
            };
        });
    });

});



let port = process.env.PORT || 4000;

app.listen(port, () => {
    console.log(`App running on port ${port} `);
});

By the look of it, the connection was undefined, did it fail to connect? If so why could I see the data in MySQLWorkbench?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

2 things:

First, you are creating a pool with invalid values. This:

const pool = mysql.createPool({
    connectionLimit: 10,
    host: "process.env.myHostname",
    user: 'process.env.myUsername',
    password: 'process.env.myPassword',
    port: "process.env.3306",
    database: 'my-schema',
    debug: false
});

SHOULD be this:

const pool = mysql.createPool({
    connectionLimit: 10,
    host: process.env.myHostname,
    user: process.env.myUsername,
    password: process.env.myPassword,
    port: process.env.myPort,
    database: 'my-schema',
    debug: false
});

Secondly, what does err look like when console.log(err)'d? Change this part:

pool.getConnection((err, connection) => {
    app.get('/my-table', (req, res) => {
        console.log(connection);
        connection.query(SELECT_ALL_QUERY, (err, results) => {
            if (err) {
                return res.send(err)
            }
            else {
                return res.json({
                    data: results
                })
            };
        });
    });

});

To this:

pool.getConnection((err, connection) => {
    if (err) {
        return console.log('ERROR!', err);
    }

    if (!connection) {
        return console.log('No connection was found.');
    }

    app.get('/my-table', (req, res) => {
        connection.query(SELECT_ALL_QUERY, (err, results) => {
            if (err) {
                return res.send(err)
            }
            
            return res.json({
                data: results
            });
        });
    });

});
over 4 years ago · Santiago Trujillo Report

0

Bro,if you will use there method createPool() with process.env don't forget of create a file .env at root project and declare variables myHostname, myUsername, myPassword and myPort. But for you test your connection more easily use this:

const mysql  = require('mysql');
const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'secret',
  database : 'your_database'
});
 
connection.connect();
 
connection.query('SELECT * FROM `my-schema`.`my-table`', function (error, results, fields) {
  if (error) throw error;
  console.log(results);
});
 
connection.end();

over 4 years ago · Santiago Trujillo Report

0

TypeError: Cannot read property 'query' of undefined

The error above is not the actual error as this occurs during query time while you should catch error during connection time, Once solution that posted by @NeoNexus DeMortis by doing this you will get the actual error.

But I will recommend verifying DB connection on application startup so at least the application will check and wait for DB connection before serving user request and it will also avoid application to went into a broken state.

pool.getConnection((err, connection) => {
    if (err)
    console.log(err)
    else{
        console.log("DB connected successfully host:",connection.config.host," DB:",connection.config.database)
        app.emit('ready');
    }
});
app.on('ready', function() { 
    let port = process.env.PORT || 4000;
    app.listen(port, () => {
        console.log(`App running on port ${port} `);
    });
}); 

In an effort to keep things simple and concise, many tutorials overlook one of the most human and intuitive aspects of JavaScript development with node. Node’s EventEmitter.

waiting-for-db-connections-before-app-listen-in-node

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!