0

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
}

2 Answers 2

1

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
    }
  };
}
Sign up to request clarification or add additional context in comments.

1 Comment

Would you mind adding sample code to achieve that? My main problem is the syntax to use
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.