问题
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