Skip to content

Instantly share code, notes, and snippets.

@ycmjason ycmjason/db.js
Created Jun 27, 2018

Embed
What would you like to do?
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);
};
},
});
},
});
@ycmjason

This comment has been minimized.

Copy link
Owner Author

ycmjason commented Jun 27, 2018

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:

MongoClient.connect('some mongo url').then(client => {
  client.db('some db name').then(db => {
    db.collection('some collection name').then(collection => {
      collection.insertOne({...});
    });
  });
});

With this script:

const db = require('./db.js');

db.members.insertOne({
  name: 'Jason Yu'
}).then(...);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.