AutoCatBackend/middleware/mongo.js
2020-02-20 21:38:28 +03:00

25 lines
532 B
JavaScript

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('autocatdev');
next();
})
.catch(function (err) {
connection = undefined;
next(err);
});
};
};