li x li x - 1 year ago 47
MySQL Question

How do I use nodejs Mysql to get my data into the function after callback

So I'm trying to use nodejs mysql to access my locally running database that I am using for development. Everything is running correctly and I am able to make successful queries to the server and get the data back.

I have the function I created below which I am module.exports so that it is accessible from within my server where it is invoked and the

method is called.

var dataStore = function (connection) {

this.con = connection;
this.clientArr = new Map();

* Loads all of the user experiences into the array.
this.loadExp = function () {

var output = 'err';

loadData(this.con, function (err, result) {
console.log(err || result);
output = result.uuid;


function loadData(con, callback) {
con.query('SELECT * FROM exp', function (err, rows, fields) {
if (err) throw err;
callback(null, rows);

* Returns the value of a client from within the hash map.
* @param id
* @returns {*|String}
this.getClient = function (id) {
var value = this.clients.get(id);
if (value != null) {
return value;
} else {
return 'err';

* Returns a full list of clients.
* @returns {Map}
this.getClientList = function () {
return this.clientArr;

* Creates a new instance of a client within the database and also within our datastore.
* @param id
* @param client
this.addClient = function (id, client) {
this.clientArr.set(id, client);


module.exports = dataStore;

Now I would like to make use of my
function outlined at the bottom of this function but I can never get my data in scope to make this possible and I'm stuck for how I would get this data in scope so that it is usable.

Answer Source

This is a problem with lexical scoping in JavaScript (ES5). You need to make sure the this is what you think it is when called. this is bound to the object the function was called within.

Look into setting var self = this at the top of your parent function and using that as a reference. Or, even better, using .bind(this).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download