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.