2

I am using ExpressJS 4 for my project and it follows MVC architecture. I created a helper where I can write commonly used functions which query data from DB (DRY approach) and these can be accessed from any controller. I'm able to call the helper functions and pass data to it but I'm unable to query the database from it.

Here's a sample of my controller (dumyController.js):

'use strict';
var dbHelpers = require('../helpers/helpers');

exports.dummyFunction = function (req, res) {
    var id=165;
    var abc = dbHelpers.dummyHelperFunction(iddd);
    console.log(abc);
};

As you can see I'm calling the helper function in the controller. Here's a sample of the helper (helpers.js)

var db = require('../db');
module.exports = {
  dummyHelperFunction: function (passvar) {
    var params = [passvar];
    var query = `SELECT email FROM members where id=?`;
    return db.query(query, params);
  }
};

In case you are wondering if there's anything wrong with my DB connection, there are no issues related to that. Still, sharing it (db.js)

var mysql = require('mysql');
var connection = mysql.createPool({
    host: '127.0.0.1',
    user: 'root',
    password: '',
    database: 'dumyDB'
});
module.exports = connection;

I'm trying to fetch the result returned by the MySQL query, but this is what I'm getting when I console.log it.

Query {
  domain: null,
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  _callback: undefined,
  _callSite:
   Error
       at Pool.query (_PROJECT-PATH_\node_modules\mysql\lib\Pool.js:199:23)
       at Object.dummyHelperFunction (_PROJECT-PATH_\helpers\helpers.js:18:15)
       at exports.dummyFunction (_PROJECT-PATH_\controllers\dumyController.js:227:25)
       at Layer.handle [as handle_request] (_PROJECT-PATH_\node_modules\express\lib\router\layer.js:95:5)
       at next (_PROJECT-PATH_\node_modules\express\lib\router\route.js:137:13)
       at Route.dispatch (_PROJECT-PATH_\node_modules\express\lib\router\route.js:112:3)
       at Layer.handle [as handle_request] (_PROJECT-PATH_\node_modules\express\lib\router\layer.js:95:5)
       at _PROJECT-PATH_\node_modules\express\lib\router\index.js:281:22
       at Function.process_params (sam_PROJECT-PATH_ple\node_modules\express\lib\router\index.js:335:12)
       at next (_PROJECT-PATH_\node_modules\express\lib\router\index.js:275:10),
  _ended: false,
  _timeout: undefined,
  _idleNext: null,
  _idlePrev: null,
  _idleStart: null,
  _idleTimeout: -1,
  _repeat: null,
  sql: 'SELECT email FROM members where id=?',
  values: [ 165 ],
  typeCast: true,
  nestTables: false,
  _resultSet: null,
  _results: [],
  _fields: [],
  _index: 0,
  _loadError: null }
version 2
  • 1,049
  • 3
  • 15
  • 36
  • 1
    [`db.query()`](https://www.npmjs.com/package/mysql#performing-queries) requires a callback function, where you can receive the result. The query is asynchronous, so you can't just `return` it. – Patrick Roberts Oct 03 '17 at 09:28
  • If I do so, what changes should I make in the controller function? I'm pretty new to nodejs @Patrick Roberts – version 2 Oct 03 '17 at 09:32
  • here is an [example with callback](https://github.com/mysqljs/mysql#introduction) – Dmitry Shvetsov Oct 03 '17 at 09:45

1 Answers1

2

Changed your code to something like the given below. db.query() is asynchronous

Controller

'use strict';
var dbHelpers = require('../helpers/helpers');
exports.dummyFunction = function (req, res) {
    var user = {
        passvar: 165
    };
    dbHelpers.dummyHelperFunction(user, function (err, rows) {
        if (err) {
            res.json({ success: false, message: 'unable to fetch' });
        }
        else {
            res.json({ success: true, values: rows });
        }
    });
};

Helper

var db = require('../db');
module.exports = {
  dummyHelperFunction: function (param, callback) {
    var params = [param.passvar];
    var query = `SELECT email FROM members where id=?`;
    return db.query(query, params, callback);
  }
};
Smokey
  • 1,857
  • 6
  • 33
  • 63