Pergunta

When querying the DB, I get this error:

TypeError: Cannot call method 'query' of undefined
    at Object.<anonymous> (/home/nodeuser/myapp_node/index.js:51:17)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

My code looks like:

var mysql = require('mysql');
var mysqlConnection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'carousel',
  debug : true,
}).connect(function(err) {
    if ( !err ) {
        console.log("Connected to MySQL");
    } else if ( err ) {
        console.log(err);
    }
});


var userId = 23

mysqlConnection.query('SELECT * FROM tusers WHERE id = ?', [userId], function(err, results) {
    console.log(err);
    console.log(results);
});

I made sure "mysql" is in node_modules. Also, I see "Connected to MySQL" in the console.

Do you know how I can make this work?

Foi útil?

Solução

The connect method that you have chained onto mysql.createConnection does not return a connection. Instead you can do:

var mysqlConnection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'carousel',
  debug : true,
});

mysqlConnection.connect(function(err) {
  if ( !err ) {
    console.log("Connected to MySQL");
  } else if ( err ) {
    console.log(err);
  }
});

Or you can leave out the connect call altogether "a connection can also be implicitly established by invoking a query" - https://github.com/felixge/node-mysql#establishing-connections

Outras dicas

I think the problem is that mysql is working on making the connection in the initialization process but your code is trying to use mysqlConnection before it is ready.

You should put your search in the spot where it says the connection is good.

Also. I think you should look at using a pool. Making a fresh connection each time is quite time consuming.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top