Open Multiple MongoDB connection in Express.js App
Tags: node, mongodb, express, javascript
Published: 2020-04-03 17:23:47

This tutorial aims to show you how to open multiple MongoDB connections in Express.js application.

Now we want to create a `package.json` file which will keep track of our dependencies information. To do that create a new file and put following content inside of it:

```json
{
  "name": "mongo-conn",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "seed": "node seeder.js",
    "dev": "nodemon index.js"
  },
  "dependencies": {
    "express": "^4.17.1",
    "faker": "^4.1.0",
    "mongoose": "^5.9.7",
    "nodemon": "^2.0.2"
  }
}
```

Let's create a new file and call it `index.js`. This file will holds our main server code. Put the following content inside `index.js` file:

```js
const express = require('express');
const {userModel, todoModel} = require('./models');
const app = express();

app.get('/users', async (req, res) => {
    const users = await userModel.find({});

    res.json(users);
});

app.get('/todos', async (req, res) => {
    const todos = await todoModel.find({});

    res.json(todos);
});

const port = 3000;
app.listen(port, () => console.log(`App listening at http://localhost:${port}`));
```

Now we will create a new file and call it `connections.js` and put following content inside of it:

```js
const mongoose = require('mongoose');

function makeNewConnection(uri) {
    const db = mongoose.createConnection(uri, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });

    db.on('error', function (error) {
        console.log(`MongoDB :: connection ${this.name} ${JSON.stringify(error)}`);
        db.close().catch(() => console.log(`MongoDB :: failed to close connection ${this.name}`));
    });

    db.on('connected', function () {
        mongoose.set('debug', function (col, method, query, doc) {
            console.log(`MongoDB :: ${this.conn.name} ${col}.${method}(${JSON.stringify(query)},${JSON.stringify(doc)})`);
        });
        console.log(`MongoDB :: connected ${this.name}`);
    });

    db.on('disconnected', function () {
        console.log(`MongoDB :: disconnected ${this.name}`);
    });

    return db;
}

const userConnection = makeNewConnection('mongodb://127.0.0.1:27017/user');
const todoConnection = makeNewConnection('mongodb://127.0.0.1:27017/todo');

module.exports = {
    userConnection,
    todoConnection,
};
```

Now lets create another file and call it `models.js` and put following content inside of it:

```js
const mongoose = require('mongoose');
const {userConnection, todoConnection} = require('./connections');

const userSchema = new mongoose.Schema({
    name: String,
    isActive: Boolean,
}, {
    versionKey: false,
    timestamps: true,
});

const todoSchema = new mongoose.Schema({
    title: String,
    completed: Boolean,
}, {
    versionKey: false,
    timestamps: true,
});

const userModel = userConnection.model('User', userSchema);
const todoModel = todoConnection.model('Todo', todoSchema);

module.exports = {
    userModel,
    todoModel,
};
```

Now lets create another file and name it `seeder.js` and put following content inside of it:

```js
const faker = require('faker');

const {userModel, todoModel} = require('./models');
const {userConnection, todoConnection} = require('./connections');

async function seed() {
    for (let i = 0; i< 10; i++) {
        await userModel.create({
            name: faker.name.findName(),
            isActive: faker.random.boolean(),
        });
    }

    for (let i = 0; i < 10; i++) {
        await todoModel.create({
            title: faker.lorem.words(3),
            completed: faker.random.boolean(),
        });
    }
}

seed().then(() => {
    userConnection.close();
    todoConnection.close();
});
```

Now open your terminal and seed your database with following command:

```bash
yarn seed
```

Lets start the application by running following command inside your terminal:

```bash
yarn dev
```

Now open the following link inside your browser:

```bash
http://localhost:3000/users
```

You can find the complete source code for this application on my [GitHub profile](https://github.com/ziishaned/multiple-mongodb-connection-example):