sangio90
sangio90

Reputation: 179

NodeJS (Express) - project structure and mongo connection

I started a new project from scratch with ExpressJS. Everything works fine but now I begin to have a dozen of 'app.get(....)' function and I need to give the project a structure.

What I have in mind is quite simple, it should have a folder named 'routes' containing a file such as 'module1.js', with all of the app.get related to that module. (like I've seen in many examples)

The issue is how to tell Express to route 'http://url/module1/' to that route file and how to pass it a param variable, containing for instance the mongodb connection.

what I tried is :

var params = { db: myMongoConnection }; var mod1 = require('routes/module1'); app.use('/module1', mod1);

but now I still miss the 'params'. If I try to pass it as an argument to the require method i get an error saying it needs middleware.

Another issue is related to the fact that the myMongoConnection is valid in the connection callback, so I think i need to require and use the route.js inside the MongoClient connect callback.

Any idea? thanks a lot


Upvotes: 1

Views: 265

Answers (1)

Swaraj Giri
Swaraj Giri

Reputation: 4037

For custom modules, create a folder, call it modules In its index.js, expose the modules that you need. Something like,

var mods = [
'mod1',
'mod2',
];

function init() {
 var expose = {};

var params = {
   db: myMongoConnection
};

mods.forEach(mods, function (mod) {
    expose[mod] = require('./' + mod)(params);
});

return expose;
}

// export init
module.exports = init;

In mod1.js, wrap the params

   module.exports = function(params) {

   // all your functions here will have access to params. 
  }

Then in, server/app.js, require this and set it in the app.

app.set('mods', require('path-to/modules'));

Now, you can access all your modules, using app.get('mods').moduleName.methodname

Upvotes: 0

Related Questions