How to connect to MongoDB using a promise in Node.js

Alex Garcia
The Startup
Published in
1 min readMay 19, 2020

--

Promise

TL;DR

Not a while ago I found myself asking myself that same question, How to connect to MongoDB using a Promise on Node.js?, after googling for a while I couldn’t find an example. I kept bumping into the same code example of a MongoDB connection using a callback:

But using this on a brand new Node.js project felt a bit dirty, so I kept looking.

After some more digging I found that The Node.js driver for MongoDB does support promises, is just that the documentation doesn’t provide an example for it.

So without further ado, this is what I went with:

The file above exports two functions, getDbConnection and closeConnection. I am using global variables _connectionand _dbto keep references to both the connection and database, this is so that if the getDbConnection is called again at any point in the application it will return the same existing DB reference instead of creating a new connection.

The global variable _connection is used by the closeConnection function.

I hope you found this helpful, let me know what you think on the comments below.

Thanks for reading.

--

--