James James - 4 months ago 10
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

start
function which returns a promise which I thought would work with the mongo native connect function. The database is connected inside the
then
. 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://127.0.0.1:27017/test", {promiseLibrary: promise})
.then(function(database) {
console.log('mongo connection initialised');
})
.catch(function(err) {
console.error('Error: ', err);
});
}

function stop() {
db.close();
}

return {
start: start,
stop: stop
}

}

module.exports = mongoFactory;

Answer

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.

Comments