Multiple databases and connections in Nodejs and MongoDB
There is a strategy in some projects that your program must read data from a database, do some processes on it, and write it in another database.
Let me give you an example, you are implementing a program that is supposed to be the “Logger” service. It collects logs from the logs database and obtains a report of them. This report will be saved in the reports database. You should separate databases because of the huge amount of data.
Implementation
So, let’s get started with setting up the project.
$ mkdir logger && cd logger
Setting up the NPM
$ npm init
Creating the entry point
$ touch app.js
Installing dependencies
$ npm i express mongoose nodemon
app.js
I don’t want to get into Architectural issues. So I want to talk about two things:
Models
Create a directory called Models
$ mkdir Models
Log.js and Report.js are the project models
Models/
├── Log.js
├── Report.js
We usually make a connection in models when we using mongoose
but this case is a little bit different
connections.js
At the root of the project create a module to handle the database connections there
connections.js has a makeNewConnection function that receives database URI and returns a connection object of that database.
We can use these connections objects in the related models
Log.js
Report.js
Each of these models is connected to the different database
That’s it. we can create layers and services around these models.
we can import Log model and read data from it, do the magic then use the Report model and save it in the Report database.
This approach is very clean and helps you to manage your database connections and not to generate spaghetti codes.
Thanks for reading this article 💖. Liked the article? have some feedback or suggestions? leave a like and a comment. This will help me understand better and write more amazing articles for you 🙂.