Created
January 24, 2019 14:47
-
-
Save bmorrisondev/fb6dc15d3880e54cbaa1c63b76cf3814 to your computer and use it in GitHub Desktop.
A mongoose connection helper script that builds a connection string from environment variables
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
| // env.test file: | |
| // DB_HOST="localhost" | |
| // DB_PORT="27017" | |
| // DB_NAME="dbname" | |
| // DB_USER="dbusername" | |
| // DB_PASS="dbpassword" | |
| require('custom-env').env(true) | |
| const mongoose = require('mongoose') | |
| exports.connect = async () => { | |
| try { | |
| let connectionString = await this.connectionString() | |
| mongoose.connection.on('error', (err) => { | |
| throw new Error(`Unable to connect to db: ${err.message}`) | |
| }) | |
| return await mongoose.connect(connectionString, { useNewUrlParser: true, useFindAndModify: false }) | |
| } catch (err) { | |
| throw new Error(`dbhelper.connect: ${err.message}`) | |
| } | |
| } | |
| exports.connectionString = () => { | |
| let connectionString = '' | |
| try { | |
| if (process.env.DB_PROTOCOL) { | |
| connectionString += `${process.env.DB_PROTOCOL}://` | |
| } else { | |
| connectionString += `mongodb://` | |
| } | |
| if (process.env.DB_USER && process.env.DB_PASS) { | |
| connectionString += `${process.env.DB_USER}:${process.env.DB_PASS}@` | |
| } | |
| connectionString += `${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}` | |
| } catch (err) { | |
| throw new Error(`dbhelper.connectionString: ${err.message}`) | |
| } | |
| return connectionString | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.