In this article, I want to show you how to reuse a MongoDB connection across routes on a NodeJS project. I'm doing this post because I was developing a project using the MongoDB official driver for node and I struggled to reuse my connection since the official docs of MongoDB show a way to use just in one file.
So, first, we need to install the mongodb driver for nodejs, you can do that using the commando below:
npm install mongodb --save
Connecting to MongoDB
Now that we installed the driver, we can start implementing the db connection, in order to do that, we'll create a file called db.js:
Using the connection anywhere we want
Now, we can use this connection anywhere in our code by just importing this method, let's see how it works!
We will now create a file app.js as an example to use the database connection.
In order to implement the routes, we'll express.js, a minimalist web framework for node, you can install using the command below:
npm install express
Our app.js file will look like this:
We'll get a JSON response that will be something like this:
Conclusion
That's it, we now can use this connection anywhere in our code!
Thanks for reading this article!
Top comments (1)
You're closing the connection after every operation and creating a new connection. How is it reusing the connection?