Share connection inside the app - nodejs


I’m not sure how to share the connection around my app, for now I have a Couchbase class that is in charge to open the connection:

class CouchBase {
  connect() {
    const self = this;
    if (self.cluster) {
      console.log("DB::connect() already opened.");
      self.bucket = self.cluster.openBucket();
      return Promise.resolve();
    self.cluster = new couchbase.Cluster('couchbase://');
    self.cluster.authenticate(process.env.DB_USER, process.env.DB_PASSWORD);
    return new Promise((resolve, reject) => {
      self.bucket = self.cluster.openBucket(this.BUCKET_NAME, (err) => {
        if (err) {
          logger.error(`DB::connect() Error: ${JSON.stringify(err)}`);
        } else {
          self.bucket.operationTimeout = 5000;
'DB::connect() OK!');

then when I start the app I’ll do something like this:

const db = new couchbase();
  .then((_db) => {
    const app = Express();
    app.use('*', (req, res, next) => {
      req.db = _db;
    app.listen(5000, () => {
      console.log("Listening at: 5000");
  }).catch((err) => {
    console.log("Error setting up the database connection: ", err);

in this case I can access the db where I have access to the request object…my problem is when I need the db but I’m not able to use the request object…do you have any advice? do I need to change somehting? how can I get the db object wihtout the request? many thanks

Hi @francesco.venica,

Next time, I’d recommend posting node-related questions to the node forum here:

In the meantime, I’m tagging @brett19 as someone who might be able to help answer your question.

There’s a sample application that shows how to wrap this in both in the documentation and at GitHub - couchbaselabs/try-cb-nodejs

@matthew.groves sure, many thanks!

@ingenthr amazing, now I’'l check this link!

many thanks!