Created
April 7, 2020 17:22
-
-
Save ctrlaltdylan/570d0e3f3936a88c393ed5cc1d9423f7 to your computer and use it in GitHub Desktop.
Mongo DB Connection
This file contains 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
// 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') | |
}); |
This file contains 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 | |
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