Search code examples
javascriptmysqlnode.jsnode-modulesecmascript-5

Getting undefined on try to connect mysql with node js using consign


I'm using consign to make the autoload from modules on my Node JS api, in this I load all my routes, models and my database connection function, When I run the nodemom app the module that makes the connection is loaded but I Cannot connect to the database, he throws me this error TypeError: Cannot read property 'db' of undefined

Look at my tree files:

enter image description here

I can load the routes cuz

db.js (File that has de database configuration)

var mysql = require('mysql');

var connMySQL = function () {
    console.log("I've Started the connection")
    return mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'agimplant'
    });
}

module.exports = function () {
    console.log("I've loaded this function")
    return connMySQL;
}

Server.js

var express = require('express'),
    bodyparser = require('body-parser'),
    consign = require('consign'),
    app = express();

consign()
    .include('./src/routes')
    .then('./src/config/db.js')
    .then('./src/models')
    .into(app);

app.use(bodyparser.urlencoded({ extended: true }));

app.listen(4000, function () {
    console.log("Servidor ON");
});

module.exports = app;

Connection Calling on Home.route.js

module.exports = function (app) {
    app.get('/', (req, res) => {
        console.log("Call the Connection Here")
        var connection = app.config.db();
    });
}

Solution

  • As discussed in the consign of the src patch, put app.src.conf for called your object. Put src for methods access always and use console.log from debbug it's is great