Created
August 12, 2020 07:17
-
-
Save bengrunfeld/36c9b6bec26d8b4bfa586e6fd44f74e7 to your computer and use it in GitHub Desktop.
Open a connection to MongoDB
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
import { MongoClient } from "mongodb"; | |
const openDbConnection = url => { | |
const p = new Promise((resolve, reject) => { | |
MongoClient.connect( | |
url, | |
{ useUnifiedTopology: true, useNewUrlParser: true }, | |
async (error, client) => { | |
if (error) { | |
reject(error); | |
return; | |
} | |
const dbName = process.env.DB_NAME || "test"; | |
const db = client.db(dbName); | |
resolve({ client, db }); | |
} | |
); | |
}); | |
p.catch(err => console.log("ERROR: openDbConnection", err)); | |
return p; | |
}; | |
const createDbConnection = async () => { | |
const host = process.env.NODE_ENV === "development" ? "localhost" : "mongo"; | |
const url = `mongodb://${host}:27017`; | |
try { | |
return await openDbConnection(url); | |
} catch (err) { | |
throw `ERROR: createDbConnection - ${err}`; | |
} | |
}; | |
export default createDbConnection; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment