2

I'm building a Serverless application using NodeJS and using MongoDB. I noticed that a lot of connections are created when handling a request. So I came up with a caching mechanism but it doesn't seem to be working. Here is my code.

Connection file

'use strict';

const connectDatabase = mongoClient => mongoClient.connect(process.env.MONGODB_STRING, { poolSize: 10 });

  const createConnection = (mongoClient, dbConnection) => {
    return new Promise(async (resolve, reject) => {
      try {
        if (dbConnection) {
          console.log('===== Cached Connection =====');
          resolve(dbConnection);
        }
        console.log('===== New Connection =====');
        let dbPool = await connectDatabase(mongoClient);
        resolve(dbPool);
      } catch (error) {
        reject(error);
      }
    });
  };

const closeDbConnection = conn => {
  if (conn) {
    return conn.close();
  }
};

module.exports = {
  connectDatabase: connectDatabase,
  createConnection: createConnection,
  closeDbConnection: closeDbConnection
};

Handler code

let admin = require('./lib/admin');
let helper = require('./lib/helper');
let connection = require('./lib/connection');
let mongo = require('mongodb');
let mongoClient = mongo.MongoClient;
let cachedDb = null;

let createUser = async (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  cachedDb = await connection.createConnection(mongoClient, cachedDb);
  admin.createUser(cachedDb, helper.parseEvent(event), callback);
};

I'm using a global variable cachedDb to store the database connection but each and every time I make a request it logs ===== New Connection ===== any idea how to achieve this. Is there a better way to handle this?.

2
  • I think just check if (dbConnection) instead of if (dbConnection && dbConnection.isConnected(dbName)), what is the dbName, maybe it is a invalid options of isConnected Commented Nov 21, 2019 at 7:11
  • @hoangdv I did that too but dbConnection is alway null I don't know why Commented Nov 21, 2019 at 8:10

1 Answer 1

3

The approach I like using here is a singleton class, like this:

export default class MyMongoConnection {
    static instance;

    static getInstance() {
        if (!MyMongoConnection.instance) {
            MyMongoConnection.instance = MyMongoConnection.createInstance();
        }
        return MyMongoConnection.instance;
    }

    static createInstance() {
        // Do whatever you need to create the instance
    }
}

So you import MyMongoConnection anywhere and just ask for the instance using .getInstance(), if it exists, it reuses it.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.