Question

I'm working with compoundjs and using the mongodb adapter of jugglingdb. I've been retrieving and reusing the native mongodb client in the controllers by doing the following:

var db = compound.orm._schemas[0].client;

This works great, as I am able to use functions that mongodb supports, such as .collection(name) and .find() on top of that. However, when I create an initializer for compoundjs, .client is empty, but it looks like _schemas[0] isn't. For example:

module.exports = function (compound) {
    var db = compound.orm._schemas[0].client; // _schemas[0] isn't empty as .client was reached.
    db.collection('collection'); // Throws: TypeError: Cannot call method 'collection' of undefined
};

How do I retrieve the native mongodb client from the jugglingdb adapter, without recreating the connection myself?

Was it helpful?

Solution

This can be accomplished by using the connected event from the JugglingDB event emitter.

module.exports = function (compound) {
    compound.orm._schemas[0].once('connected', function () {
        var db = compound.orm._schemas[0].client;
        db.collection('Module');
    });
};

Explanation:

When JugglingDB loads an adapter, it passes in a finished callback, which triggers the connected event. When loading the mongo adapter, the adapter uses an async call to connect to the database, which could cause initializers to run before the adapter is fully connected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top