Search code examples
node.jsnode-mysql

node.js node-mysql query not working


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?


Solution

  • 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