Returning Connected MongoClient to Plugin: SOLVED



  • EDIT: SOLVED - SEE BELOW REPLY

    I've been searching for a few days and managed to hack together an implementation; but it's not correct.

    I would like to have access to my connected MongoClient in my plugin so I can access the database via the 'db.client.collection('colName').find({})' functionality; and other similar functionality through the MongoDB docs.

    I understand that I can use the db.getObject and such from the database layer (./src/database) but I want to write some custom methods that are based off of lower level calls to the db.

    Currently, my hacked-together plugin just creates a new connection and then closes it which is absolutely horrible for performance.

    I want to tap into the connection that's already present upon app startup and simply have access to the db object that will give me access to my 'nodebb' database.

    Any help with this would be greatly appreciated; thanks.



  • So I ended up answering my own question:

    If you would like to tap into your db object from within a plugin and use mongoDB's native functions, 'db.client' will provide them.

    Example:

            var db = module.parent.require('./database');
    	
    	function getResult(req, res, next, callback){
    		 var data = db.client.collection('objects').find({cid: "1"}).toArray()//Query whatever
        		.then(function(data) {//Pass the promise through a callback
         			console.log(data.length); // Use this to debug
          			callback(req, res, data, next)//Send data to your render function or where ever
       			})
    	}
    

    Hope this saves someone else some time if they're trying to achieve the same thing!


Log in to reply
 


Looks like your connection to NodeBB was lost, please wait while we try to reconnect.