1

how do i share the db object returned from when i call db.open or db.connect across the entire app?

i have a dbconnect.js module as follows :

var mongodb = require('mongodb');
var global_db  = '';

// Define options. Note poolSize.
var serverOptions = {
   'auto_reconnect': true,
   'poolSize': 5
};

// Now create the server, passing our options.
var serv = new mongodb.Server('localhost', 27017, serverOptions);

// At this point, there is no connection made to the server.

// Create a handle to the Mongo database called 'myDB'.
var dbManager = new mongodb.Db('myDB', serv);

// NOW we initialize ALL 5 connections:
dbManager.open(function (error, db) {
  // Do something with the connection.
  global_db = db;
  // Make sure to call db.close() when ALL connections need
  // to be shut down.
  db.close();
});

function getConnection()
{
   return global_db;
} 

exports.getConnection = getConnection;

and i am using this dbconnect.js in my app.js as:

var http = require('http');
var db = require('./dbconnect').getConnection();
var collection = db.collection('testcollection');
console.log(db);
console.log(collection);

var server = http.createServer();

server.on('request',route);

server.listen(8000,'127.0.0.1');

console.log('Server running at http://127.0.0.1:8000');

function route(request,response)
{
    var url = request.url;
    var doc = {};
    doc[url] = 'ok';
    collection.insert(doc,{w:1},function(err,result)
        {
            if(err) console.log(err);
            else console.log(result);
        });
}

in the console, the db and collection variable show empty values, i also tried removing the db.close() call in dbconnect.js but to no use, however the insertion works when i place it inside dbconnect.js file in the dbManager.open function, how do i do this?or any similar alternatives?

1 Answer 1

2

You can't do that, because dbManager.open( is async method, but you trying to get data from module synchronously.

Try this:

In dbconnect.js

var on_db_ready = null;
module.exports = {
                db_ready:function(db_ready_callback){
                     on_db_ready = db_ready_callback;
                     //here we call callback if already have db
                     if (global_db) on_db_ready(global_db);
                 },
                 getConnection:getConnection
                };
dbManager.open(function (error, db) {
 if (on_db_ready) on_db_ready(db);
  global_db= db;
})

in app.js:

var db = require('./dbconnect').db_ready(function(db){
  //Here i have my database
  //or can use getConnection method
});

this is not very beautiful way, but, I hope, explain your mistake

Sign up to request clarification or add additional context in comments.

4 Comments

Yep, this worked, thanks, what do you mean by not a very beautiful way?How to keep the dbobject cached and pooled if not in this way?
I mean that is not elegant\beautiful code. I like creating functions such as "db_ready" through deferred objects. Also usually, after "getDatabase" in mongodb I use "getCollection" method, so I prefer cache collections instead of db's. It makes less and more readable code. Like db_cache.getCollection("users")(function(coll){....});
ok, i thought of using the same method, but the collections i use are not pre-defined, hence i wanted the db object, but thank you.
you can use collections caching without export db from this module. Just request collection in future "getCollection" method inside module, and before returning it - put it to cache. then you can get already existed collection.

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.