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

心已入冬 提交于 2019-12-22 09:30:53

问题


I'm writing a remote method that would be greatly enhanced by running an aggregation pipeline query.

To do that I need to get the actual mongodb connection and work with it directly.

How can I run something along the lines of

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

I have mongo defined in my datasources.json as

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

回答1:


Okay, did a little more digging, mostly into the loopback and mongo connector source code. If you want to get direct access to the mongoDB connection you can, but be careful!

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

};


来源:https://stackoverflow.com/questions/28346169/how-do-i-get-the-mongodb-connection-from-inside-loopback-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!