loading...

re: Open Multiple MongoDB connection in Express.js App VIEW POST

FULL DISCUSSION
 

Nice!
Is there anyway await the multiple DB connections before the server start listen http traffic? I never had founded a nice way to do that : (

 

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;

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}`));
 

Thanks for your quick reply! I will try your suggestion

code of conduct - report abuse