如何从Loopback.io内部获取MongoDb连接 [英] How do I get the MongoDb connection from inside Loopback.io

查看:179
本文介绍了如何从Loopback.io内部获取MongoDb连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我该如何遵循

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定义为

I have mongo defined in my datasources.json as

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

推荐答案

好吧,我做了更多的挖掘工作,主要研究回送和mongo连接器源代码.如果您想直接访问mongoDB连接,可以,但是要小心!

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

};

这篇关于如何从Loopback.io内部获取MongoDb连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆