2015-02-05 69 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