Created
June 27, 2018 21:50
-
-
Save ycmjason/404c7005cace89b1ab59b10310d6637c to your computer and use it in GitHub Desktop.
A neat way to interact with mongoclient, without caring too many proxies.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
The main advantage of this script is you won't need to worry about all the intermediate promises but only focus on the actual operation u wanna perform
Example usage:
Without this script:
With this script: