Idiomatic appraoch to sharing mongodb connection?

Hello, I recently completed the URL Shortener Microservice challenge, during which I had to use Express and MongoDB to perform finds and inserts on a collection of submitted urls.

An architectural question arose when I had to use mongodb connection in two separate routes. The github repo showcases my take on this problem. Simply put, I connect to mongodb as soon as application starts and take it on faith that connection will be established before any requests to the server would be made.

I’m interested to know how different people solve similar problem, if there’s a programming pattern for it. I kinda want to overengineer this case, because I fail to see how my naive solution would translate to serious projects.

Github Link:
Project Link:

Hey, why do you use the http module if you use express for the rest? To your question: You can put the server.listen() in the callback of the mongodb.connect function. This will make sure that the app only starts when the db is connected.


The way I see it, using MongoDB without Mongoose is like eating PB&J without bread - confusing, messy, and unsatisfying. Mongoose takes care of your connections for you, as well as imposing a schema on your data, which helps prevent bugs and makes way more sense. That said, the way you’re doing it seems to be the official recommendation, which I would not have guessed.


I used http module to get access to server instance and print friendly message upon its startup. I learned of this approach from express-generator’s boilerplate code. Your suggestion is very handy, it’s something I haven’t considered. Thanks.

Thanks your link could not have been any more relevant. I’m pleased to know I figured the right path. Mongoose looks interesting too, at some point I may try to figure out how things are handled under the hood there.