Tuesday 17 October 2017

[Code review request] Reuse MongoDB connection in Express application

I've already asked for a code review in stackoverflow, with no luck, so I thought I'd ask here as well.I think the title is pretty straightforward. I implement a client for MongoDB and I want to include it anywhere in my app and share the connection (not create it always or close it always).So my question is, what are the downsides of this implementation? I've noticed that if I don't explicitly call disconnect the app never finishes / closes. Am I doing something wrong here? What are your suggestions to increase the re-usability and quality of my code? Thanks!const mongodb = require('mongodb'), MongoClient = mongodb.MongoClient, dbName = 'ppl', collection = 'pp', mongoUrl = `http://mongodbip-and-port/${dbName}`, { promisify } = require('util'); let db; class Mongo { static connect() { return new Promise((resolve, reject) => { MongoClient.connect(mongoUrl, (err, database) => { if (err) { reject(err); } db = database; resolve(); }); }); } static disconnect() { return new Promise((resolve, reject) => { try { db.close(); resolve(); } catch (error) { reject(error); } }) } static insertMany(data) { return new Promise((resolve, reject) => { try { const col = db.collection(collection); col.insertMany(data, (err, returns) => { resolve({ err, results: returns.insertedCount }); }); } catch (error) { reject(error); } }); } } module.exports = Mongo;

Submitted October 17, 2017 at 03:11PM by JavascriptFanboy

No comments:

Post a Comment