1

I m trying to make the most effective way of writing a mongodb connection setup for an express based node js app.

I have made a class that takes care of connection set up as follows:

class queryToDB {
    async makeDBCall(queryHandler)   {
        let resultSet;
            await MongoClient.connect(config.mongodburl, (err, client) => {
                if(err) throw Error("Database connection cannot be established.");
                resultSet = queryHandler(client.db("dbname"));
                client.close();
            });

        return resultSet
    }
};


export default new queryToDB();

After each query, I m closing the connection to the MongoClient. Is it the advised way to do it ?

Secondly, I m passing the connection to a callback as queryHandler. The queryHandler function would look something like this:

export const getCall = (id, handler) => {
    return connection => {
        connection.collection('some_schema').findOne({"_id": getObjectId(id)}, (err, result) => {
            if(err) throw new Error(err);
            handler(result);
        });
    }
};

I m passing the result back to the handler which in turn is passed back to the client from the server. Is this an effective way of creating connections and handling results ? So far I haven't done any kind of load testing on this but want to be sure if there is any issue with this approach of handling of queries and result to mongodb. I m also aware that I m using a couple of callbacks to achieve this, which is why I want to know more about the performance of this approach. I don't want to use Mongoose for this work. I m looking for just implementing this with MongoClient. Any kind of feedback is appreciated. Thanks.

Pranay Tripathi
  • 1,614
  • 1
  • 16
  • 24
  • 1
    You absolutely do not want to be opening and closing MongoClient each request. See https://stackoverflow.com/questions/14495975/why-is-it-recommended-not-to-close-a-mongodb-connection-anywhere-in-node-js-code – JohnnyHK Nov 27 '18 at 01:57

0 Answers0