2015-02-05 70 views
3

我在写一个远程方法,通过运行聚合管道查询将大大增强该方法。如何从Loopback.io中获取MongoDb连接

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

如何运行沿着我的datasources.json我已经蒙戈定义的

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'} 
    }); 
}; 

行的东西作为

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

即使有一种方法可以通过回送获取连接信息,然后直接使用node.js打开一个新的连接并使用它,那会是我想的。 – Drew 2015-02-05 14:15:32

+0

这不是一个理想的解决方案,我认为...但是你总是可以只抓取数据源配置,并创建一个到数据库的新连接:'var config = require('../../ server/datasources。 json')。MongoDB;'我会看看我能否找到其他任何东西。 – jakerella 2015-02-05 16:31:23

回答

7

好吧,确实有点多挖掘,多到环回, mongo连接器源代码。如果你想直接访问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 

}; 
+0

这工作。谢谢= D – Drew 2015-02-09 14:14:47