DEV Community

Discussion on: Open Multiple MongoDB connection in Express.js App

Collapse
 
ziishaned profile image
Zeeshan Ahmd • Edited

To do that you have to import the file which contains the MongoDB connection code into main server file. Please have a look at the following code:

Put following code inside connection.js file:

const db = mongoose.createConnection('mongodb://127.0.0.1:27017/user', {
    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}`);
});

module.exports = db;
Enter fullscreen mode Exit fullscreen mode

Now create another file and call it index.js and put following code inside of it:

const express = require('express');
require('./connection');

const app = express();

const port = 3000;
app.listen(port, () => console.log(`App listening at http://localhost:${port}`));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
janguianof profile image
Jaime Anguiano

Thanks for your quick reply! I will try your suggestion