0

How to manage mongodb connections in a nodejs webapp?

The answer of that question is superb. I would like code however to show this. I've tried the following but since it connects async the connection is not ready by the time I want to do my database query. I'm wondering how do others do this?

'use strict';

// database stuff
var mongodb = require('mongodb'); // mongodb drivers
var MongoClient = mongodb.MongoClient; // interface
var url = 'mongodb://127.0.0.1:27017/self';
// generator flow control
var co = require('co');

// database connect function
var dbConnect = function (url) {
    // get the db object
    MongoClient.connect(url, {
        safe: true
    }, function (err, db) {
        if (err) throw err;
        console.log('mongodb connection successful');
        return db;
    });
};

var db = dbConnect(url);

// generator function with flow control
co(function* () {
    console.log('starting db query');

    // count documents in collection
    var result =
        yield new Promise(function (resolve, reject) {
            if (err) reject(err);
            db.collection('test').count(function (err, res) {
                if (err) reject(err);
                resolve(res);
            });
        });
    // output number of documents in collection
    console.log(result);
});

// more code....

I would like to use the variable db anywhere in my app.

basickarl
  • 37,187
  • 64
  • 214
  • 335
  • Notice your `dbConnect` function doesn't return anything, so `db === undefined`. – Patrick Roberts Jan 25 '16 at 10:03
  • The connect function return the connected db in Async function. If you want to use db in anywhere unless you make sure other operation on db is later on the connection is ready. – zangw Jan 25 '16 at 10:25

2 Answers2

0

Here maybe one way to reuse the connection.

var myDb;

//reuse connection if already created
function connect(callback) {
  if (myDb === undefined) {
    MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
      if(err) { return callback(err)};
      myDb = db;
      callback(null, db);
    });  
  } else {
    callback(null, myDb);
}

function doDBOperation(err, db) {
   // your mongodb operation through db is here
   co(function* () { ...
}

connect(doDBOperation);
zangw
  • 43,869
  • 19
  • 177
  • 214
0

You can wrap your database connection into promise and wait it in generator

function connect() {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, {safe: true}, (err, db) => {
            if (err) return reject(err);
            resolve(db);
        });
    });
}

var dbConnection = connect();

co(function* () {
    var db = yield dbConnection;

    // your code
});
Alexey B.
  • 11,965
  • 2
  • 49
  • 73