Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

703
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda