I am wondering what the best way is to reuse db connections in my case its couchebase connection in NodeJs as well as express. For the Express part i created a middleware like this
var couchbase = require('couchbase')
var config = require('../config/config')
module.exports = (req,res,next)=>{
var cluster = new couchbase.Cluster(config.cluster)
cluster.authenticate(config.userid, config.password)
let bucket = cluster.openBucket(config.bucket);
bucket.manager().createPrimaryIndex(function() {});
req.bucket = bucket;
req.N1qlQuery = couchbase.N1qlQuery;
next();
}
which works fine in the express app since i tell it to
const dbSessionMiddleware = require('../middleware/couch')
app.use(dbSessionMiddleware)
which allows me to access it via req.bucket . My issue is that i have controllers in my app which in case might call a helper function and they might call another function to get some data back. I want to avoid to have to keep passing the request object down 5 levels or so to use the middleware. Is there a better way how i can expose the connection / bucket to normal functions ?