3

I'm developing an express app that provides a REST api, it uses mongodb through mongoskin. I wanted a layer that splits routing from db acess. I have seen an example that creates a database bridge by creating a module file, an example models/profiles.js:

var mongo = require('mongoskin'),
db = mongo.db('localhost:27017/profiler'),
profs = db.collection('profiles');

exports.examplefunction = function (info, cb) {
  //code that acess the profs collection and do the query
}

later this module is required in the routing files.

My question is: If I use this aproach for creating one module for each collection, will it be efficient? Do I have an issue of connecting and disconnecting multiple(unnecessary) times from mongo by doing that?

I was thiking that maybe exporting the db variable from one module to the others that handle each collection would solve the suposed issue, but I'm not sure.

ojon
  • 323
  • 1
  • 3
  • 7

1 Answers1

0

Use a single connection and then create your modules passing in the shared db instance. You want to avoid setting up separate db pools for each module. One of doing this is to construct the module as a class.

exports.build = function(db) {
 return new MyClass(db);
}

var MyClass = function(db) {
  this.db = db;
}

MyClass.doQuery = function() {
}
christkv
  • 4,370
  • 23
  • 21
  • I'm doing this: in one file I put var mongo = require('mongoskin'); exports.db = mongo.db('localhost:27017/profiler'); – ojon Sep 27 '12 at 19:54
  • in the other modules: var db = require('../ds/config.js').db; – ojon Sep 27 '12 at 19:57
  • config.js is the first file, does it has the same effect? I'm not sure how node handles the same require in multiple files. – ojon Sep 27 '12 at 19:58