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

时间:2015-02-05 14:12:23

标签: mongodb loopbackjs

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

要做到这一点,我需要获得实际的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"
  }
}

1 个答案:

答案 0 :(得分:8)

好的,做了一点挖掘,主要是关于loopback和mongodb连接器源代码。如果你想直接访问mongoDB连接,你可以,但要小心!

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

};