Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Created June 27, 2018 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ycmjason/56e43bf9358b33cbc816004046a006a5 to your computer and use it in GitHub Desktop.
Save ycmjason/56e43bf9358b33cbc816004046a006a5 to your computer and use it in GitHub Desktop.
A neat way to interact with mongoclient, without caring too many proxies.
const MongoClient = require('mongodb').MongoClient;
const DB_NAME = 'mydb';
const MONGO_URL = process.env.MONGO_URL;
const dbPromise = MongoClient.connect(
MONGO_URL,
{ useNewUrlParser: true },
).then(client => client.db(DB_NAME));
// if anything went wrong connecting db
dbPromise.catch(e => {
console.error(e);
console.error('Cannot connect to mongodb...');
process.exit(1);
});
module.exports = new Proxy({}, {
get(target, collectionName) {
return new Proxy({}, {
get(target, methodName) {
return async (...args) => {
const collection = await dbPromise.then(db => db.collection(collectionName));
return collection[methodName](...args);
};
},
});
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment