I am trying to initialize a mongo Singleton connection with expressjs in the app/server.js file, in an async manner. I want to use the native driver and not Mongoose or something similar.
The whole internet is filled with bad patterns (IMHO) that open a new connection with each request.
Has anyone tried and succeeded in the former? Any link or advise will be appreciated.
For example
// app.js
let client = await initMongoConnection()
Top comments (7)
What I do is initialize the database connection, plus any other asynchronous initialization I need to do, and then bootstrap the entire application and send the connection to any component that needs it.
So basically what your snippet is hinting at:
You can check this project I built a while ago for a complete example.
Your approach looks very interesting. And cleverly simple as hell. I was trying to do it strictly with await calling anonymous functions on the fly, but this looks very promising :)
Thanks a lot
Glad it helped :)
I hope this was an intended pun :D
hahaha, no I just noticed what I did :D
if you are using mongoose then you can create a
mongoose.js
as a middleware where you initialize your connection like so:and then in your
server.js
you can call any mongoose model after this without initializing the connection again
I've used a few patterns:
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.
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