I’m in the early stages of a new project, which is going to be a Koa server (Node) utilizing the MongoDB Node driver. Fair warning: I may not use exactly correct terminology - I feel like I’m fumbling around in the darkness here as I learn how to put all the pieces together.
I’m wanting to ensure that my MongoDB connection opens when the server starts, and that it tidily closes during a shutdown sequence.
Right now, my server is structured as such:
app.js starts a Koa server, defines the middleware stack, and the Koa instance is exported as app
(an object).
server.js imports app
and listens on a port. I think this is where I should fire up the Mongo connection - but I can’t conceptualize how I would pass it to app
for use.
Further, the middleware of app
will make calls to handler methods in another directory to handle business logic (including DB interaction) - so it is not even app
itself that is using the Mongo connection app
's middleware calls functions that use the Mongo connection.
I hope I’ve made myself clear - I made every effort to. If what I’m describing seems weird, it may not be because I did a poor job describing it - it may be because this is my first run-through of building a backend from the ground up. All constructive criticism is appreciated.