如何从 Loopback.io 内部获取 MongoDb 连接

How do I get the MongoDb connection from inside Loopback.io

我正在编写一个远程方法,运行聚合管道查询会大大增强它。

为此,我需要获得实际的 mongodb 连接并直接使用它。

我怎样才能 运行 遵循

module.exports = function(ZipCodes) {
    ZipCodes.pipeline = function (cb) {
        //Get the MongoDB Connection
        var mongodbConnection = ***whatever magic***

        var result = mongodbConnection.db.zipcodes.aggregate( { $group :
                         { _id : "$state",
                           totalPop : { $sum : "$pop" } } },
                       { $match : {totalPop : { $gte : 10*1000*1000 } } } );
        cb(result);                    
    };

    ZipCodes.remoteMethod('pipeline', {
        returns: {arg: 'zips', type: 'array', root: false},
        http: {path:'/pipeline', verb: 'get'}
    });
};

我在 datasources.json 中将 mongo 定义为

{
  "db": {
    "name": "db",
    "connector": "memory"
  },
  "MongoDB": {
    "host": "localhost",
    "port": 27017,
    "name": "MongoDB",
    "connector": "mongodb"
  }
}

好的,做了更多的挖掘,主要是回环和 mongo 连接器源代码。如果您想直接访问 mongo 数据库连接,您可以,但要小心!

module.exports = function(ZipCodes) {
    ZipCodes.pipeline = function (cb) {
        //Get the MongoDB Connection
        var mongodbConnection = ZipCodes.dataSource.connector.db;
        if (!mongodbConnection) {
            // may not be connected yet, you might have to do that manually:
            // (careful! this is asynchronous)
            ZipCodes.dataSource.connect(function(err, db) {
                mongodbConnection = db;
            });
        }

        // do whatever you need to with the mongo connection...
        cb(result);
    };

    // ... other stuff

};