Skip to content

Instantly share code, notes, and snippets.

@ctrlaltdylan
Created April 7, 2020 17:22
Show Gist options
  • Save ctrlaltdylan/570d0e3f3936a88c393ed5cc1d9423f7 to your computer and use it in GitHub Desktop.
Save ctrlaltdylan/570d0e3f3936a88c393ed5cc1d9423f7 to your computer and use it in GitHub Desktop.
Mongo DB Connection
// require('koa') or require('express') whatever fits your fancy
const { Connection } = require('./db');
Connection.connectToMongo().then(() => {
// initialize your app and register routes
router.get('whatever', async(ctx) => {
const result = await Connection.db.collectionName.find({ id: ctx.params.id });
ctx.res.body = result;
// yay CRUD
})
})
.catch((err) => {
console.log('whoops database ain\'t working there bud')
});
const MongoClient = require('mongodb').MongoClient
class Connection {
static db;
static url = 'mongodb://127.0.0.1:27017'
static options = {
poolSize: 10,
}
// connect to the mongodb
static async connectToMongo() {
if (this.db) return this.db
this.client = await MongoClient.connect(this.url);
this.db = this.client.db('YOUR_DB');
return this.db
}
}
module.exports = { Connection }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment