Reputation: 12212
I would like to export the variable db
so it would be available in app.js
app.js
'use strict';
var config = require('./config');
console.log(config);
var database = require('./services/database')(config);
database.connect(...) // database is undefined
Exception: TypeError: Cannot call method 'connect' of undefined
config.js
var config = module.exports;
config.mongodb = {
port: process.env.MONGODB_PORT || 27017,
host: process.env.MONGODB_HOST || 'localhost',
db: "test"
};
services/database.js
module.exports = function(config) {
var mongoskin = require('mongoskin');
console.log(config);
var dburl = config.mongodb.host + ":" + config.mongodb.port + "/" + config.mongodb.db + "?auto_reconnect";
console.log(dburl);
var db = mongoskin.db(dburl);
// I want to export db
}
Upvotes: 0
Views: 873
Reputation: 39437
I would export an object which has db property. That object may have other properties (function/data) too. This sample code exports an object with a function property fun and a data property db.
module.exports = function(param) {
return {
fun : function() {
// whatever code is needed
},
db : {
// whatever data is needed
}
};
}
Upvotes: 1
Reputation: 3490
Node cache modules' value so it's always will return same db instance.
services/database.js
module.exports = function(config) {
var mongoskin = require('mongoskin');
console.log(config);
var dburl = config.mongodb.host + ":" + config.mongodb.port + "/" + config.mongodb.db + "?auto_reconnect";
console.log(dburl);
var db = mongoskin.db(dburl);
return db;
};
Also, you don't need to database.connect in app.js, because you are already connected in services/database.js.
Upvotes: 1