0

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?

2 Answers 2

5

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

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

Comments

0

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.

3 Comments

I modified the code to use pool, and it started working. Maybe the pool connection is faster. Is there a way to do this synchronously?
I'm not sure how that could be done. What is it you are trying to achieve?
Here is a dB module I built for a project. Perhaps it will give you some ideas about how to organize things: kleelof.com/db.zip

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.