Skip to content

Instantly share code, notes, and snippets.

@bengrunfeld
Created August 12, 2020 07:17
Show Gist options
  • Save bengrunfeld/36c9b6bec26d8b4bfa586e6fd44f74e7 to your computer and use it in GitHub Desktop.
Save bengrunfeld/36c9b6bec26d8b4bfa586e6fd44f74e7 to your computer and use it in GitHub Desktop.
Open a connection to MongoDB
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