DEV Community

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

Collapse
 
avalander profile image
Avalander • Edited

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:

initDatabase()
  .then(startApp)

const startApp = db => {
  const app = express()
  app.use('/', makeApi(db))
  app.listen(PORT, () => console.log(`Server started on port ${PORT}`))
}

You can check this project I built a while ago for a complete example.

Collapse
 
perigk profile image
Periklis Gkolias

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

Collapse
 
avalander profile image
Avalander

Glad it helped :)

this looks very promising

I hope this was an intended pun :D

Thread Thread
 
perigk profile image
Periklis Gkolias

hahaha, no I just noticed what I did :D