let MongoClient = require('mongodb').MongoClient; module.exports = function (uri) { if (typeof uri !== 'string') { throw new TypeError('Expected uri to be a string'); } let connection = null; return function expressMongoDb(req, res, next) { if (!connection) { connection = MongoClient.connect(uri, { useUnifiedTopology: true }); } connection .then(function (client) { req['db'] = client.db('autocat'); next(); }) .catch(function (err) { connection = undefined; next(err); }); }; };