DEV Community

Discussion on: How to initialize a Singleton mongo connection with expressjs

bradtaniguchi profile image

I've used a few patterns:

  1. Create a connection to the DB before the app starts, provide the db connection to who needs it. @avalander provided an example.
  2. Create a map of database connections. This is the same as the first setup, but allows you to have multiple db connections open in a "pool" based upon users. (This was done due to having to connect to multiple databases)
  3. Use Dependency Injection using a lib, your own, or framework (hello nestjs)

I personally find the DI setup is the easiest, but requires the most legwork to get setup. The architecture scales better once you have more dependencies, or dependencies of dependencies or more complexity beyond waiting for 1 thing to "load". (you need to get a config to load before starting mongo, passing extra DB connections to multiple controllers, etc)

Generally opening 1 mongodb connection per request is the worst way to go about things, unless you only have 1 endpoint and or client-side caching or some other layer of caching.

perigk profile image
Periklis Gkolias Author

Apart from too many articles, I have seen in actual apps too, unfortunately (the one connection per request). I will have a look at nest.js