1

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?

3 Answers 3

3

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
            });
        });
    });

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

2 Comments

Thank you for the answer, myHostName contains this eu-west-2.rds.amazonaws.com, which gives me error An identifier or keyword cannot immediately follow a numeric literal at rds, which was why I transformed it into a string?
The above error was resolved by removing process.env and wrapping the hostName in double quotes like this host: "myHostName"
2

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();

Comments

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

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.