Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

713
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda