stackdave stackdave - 13 days ago 4
Javascript Question

express 4 router with express.Router(), how to get a global database connection?

how can pass a global variable in node from a file to a module ?
I'm trying with a db variable that is a database mongo connection.I copy the contents of file for the connections that i was trying to do, but did not work, have no errors in console; just in my browser got error 500.

app.js

var express = require('express');
var accounts = require('./routes/accounts');

var app = express();
app.set('port', process.env.PORT || 3000);


app.use('/accounts', accounts);

app.use(function(req, res) {
res.type('text/plain');
res.status(404);
res.send('404 - Not Found');
});

// custom 500 page
app.use(function(err, req, res, next) {
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server Error');
});

var mongoUtil = require( './mongoUtil');

mongoUtil.connectToServer( function( err ) {


app.listen(app.get('port') , function() {
console.log('Express started in ' + app.get('env') +
' mode on http://localhost:' + app.get('port') +
'; press Ctrl-C to terminate.');
});
} );


mongoUtils.js

var MongoClient = require( 'mongodb' ).MongoClient;
const assert = require('assert');

var dbclass = module.exports = {

db : null,

connectToServer: function( callback ) {

var url = 'mongodb://localhost:27017/crm1';

MongoClient.connect(url, function(err, db) {
if(err) throw err;

console.log("Connected successfully to server");


dbclass.db = db;


});


},

getDb: function() {
return dbclass.db;
}
};


/router/accounts.js

var express = require('express');

var router = express.Router();
var db = .... ??? ;


router.get('/', function(req, res) {
findDocuments(db, function() {
db.close();
});

});

router.post('/', function(req, res) {
res.send('POST handler for /dogs route.');
});



var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('accounts');
// Find some documents
collection.find().toArray(function(err, docs) {

console.log("Found the following records");
console.log(docs);
callback(docs);

});


}

module.exports = router;

Answer

I've rewrittenthe code following @DrakaSAN ideas; my code had errors, i've changed in a betther way:

app.js

let express = require('express');

let app = express();
app.set('port', process.env.PORT || 3000);

let dbMongo = require( './db/dbMongoNative');


dbMongo.init ( function( error ) {

    if (error)
        console.error(error);

    let accounts = require('./routesMongoNative/accounts');
    accounts.init();

    app.use('/accounts', accounts.getRouter());

    app.get('/',function(req, res) {
        res.send('hello');
    });


    app.use(function(req, res) {
        res.type('text/plain');
        res.status(404);
        res.send('404 - Not Found');
    });

    // custom 500 page
    app.use(function(err, req, res, next) {
        console.error(err.stack);
        res.type('text/plain');
        res.status(500);
        res.send('500 - Server Error');
    });

    app.listen(app.get('port') , function() {
        console.log('Express started in ' + app.get('env') +
            ' mode on http://localhost:' + app.get('port') +
            '; press Ctrl-C to terminate.');
    });
} );

/db/dbMongoNative.js

var MongoClient = require( 'mongodb' ).MongoClient;

module.exports.init =  function (callback) {

    var url = 'mongodb://localhost:27017/crm1';

    MongoClient.connect(url, function (error, db) {
        if (error) {
            console.error(error);
        }

        console.log("Connected successfully to server");

        module.exports.db = db;

        console.log('end connect');
        callback (error);

    });
};

/routesMongoNative/accounts.js

var express = require('express');
var router = express.Router();
var dbMongo  = require( '../db/dbMongoNative' );

let db = dbMongo.db;  // connection was done before in app

let findAll = function(res, db ) {
    db.collection('accounts').find( {}).toArray( function( error, result ) {
        if (error) throw error;
        res.json(result);

    });
};

function init() {
    router.get('/', function(req, res) {
        findAll(res, db );

    });
}


function getRouter() {
    return router;
}

module.exports = {
    init: init,
    getRouter: getRouter
};