25 lines
509 B
JavaScript
25 lines
509 B
JavaScript
import { MongoClient } from 'mongodb';
|
|
|
|
export default function expressMongoDb(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);
|
|
}
|
|
|
|
connection
|
|
.then(function (client) {
|
|
req['db'] = client.db(process.env.DB_NAME);
|
|
next();
|
|
})
|
|
.catch(function (err) {
|
|
connection = undefined;
|
|
next(err);
|
|
});
|
|
};
|
|
} |