Skip to content

Instantly share code, notes, and snippets.

@loucadufault
Created January 13, 2022 02:23
Show Gist options
  • Save loucadufault/27a844073a6c91bf1e900fee127c0290 to your computer and use it in GitHub Desktop.
Save loucadufault/27a844073a6c91bf1e900fee127c0290 to your computer and use it in GitHub Desktop.
A simple pattern for opening a mongoose connection to a MongoDB database while registering listeners on the connection and handling the asynchronous result of opening the connection.
import mongoose from "mongoose";
function getConnection(databaseURL, connectionListeners) {
return mongoose.connection;
}
async function openConnection(databaseURL, options) {
await mongoose.connect(databaseURL, options);
}
export { getConnection, openConnection };
import { getConnection, openConnection } from "./database";
const databaseURL = process.env.DATABASE_URL;
const dbConnection = getConnection();
dbConnection.on(
"error",
logger.error.bind(logger, "mongoDB connection error:")
);
dbConnection.once("open", () => {
logger.info("Connected to MongoDB");
});
// avoid top-level await
openConnection(databaseURL).then(
(mongooseInstance) => {
logger.info("Ready to use mongoose instance");
},
(e) => {
logger.error("Initial mongoose connection error");
unexpectedErrorHandler(e);
}
);
function exitHandler() {
if (server) {
server.close(() => {
logger.info("Server closed");
process.exit(1);
});
} else {
process.exit(1);
}
}
function unexpectedErrorHandler(error) {
logger.error(error);
exitHandler();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment