James James - 1 year ago 41
Node.js Question

Kontainer-di with Mongo Native

I'm trying to get the MongoDB Native Driver to work with Kontainer-di. I want to add the connected client (returned from the connect method) to the container so that I can inject it into the controllers/services directly.

There is an option to use a

function which returns a promise which I thought would work with the mongo native connect function. The database is connected inside the
. My issue is that I'm not sure how I can access the connected database client to add the session to the container.

My code so far looks like:

var mongoClient = require('mongodb').MongoClient;
var promise = require('bluebird');

var mongoFactory = function(config) {

function start() {
return mongoClient.connect("mongodb://", {promiseLibrary: promise})
.then(function(database) {
console.log('mongo connection initialised');
.catch(function(err) {
console.error('Error: ', err);

function stop() {

return {
start: start,
stop: stop


module.exports = mongoFactory;

Answer Source

In case somebody else has the same issue as me. I ended up going with the mongojs library instead which doesn't use promises for the connection so the active connection could easily be added to the container.

I still wanted to use promises rather than callbacks for the queries so I used bluebird and it's promisifyAll method.