How do I get the native mongodb client from a jugglingdb adapter during compoundjs initialization?

StackOverflow https://stackoverflow.com/questions/21840828

質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top