Mohamed Mahmoud
Mohamed Mahmoud

Reputation: 111

Connecting to many databases at once in mongo/mongoose

We are trying to connect to 1500 databases using mongoose but it's too slow to create 1500 connection with 1500 DB using this command

mongoose.createConnection(url);

the 1500 DB are on the same database server. it took more than 50 minutes to establish these connections.

Is there any way to decrease the amount of time or is there a way to connect to the 1500 DB at once as they are on the same server?

Upvotes: 4

Views: 704

Answers (1)

DrakaSAN
DrakaSAN

Reputation: 7853

You could try async:

'use strict';
const mongoose = require('mongoose'),
    async = require('async'),
    dbsUrl = [
    'mongodb://url1',
    //...
    'mongodb://url15000',
];

async.map(dbsUrl, (url, callback) => {
    let conn = mongoose.createConnection();
    conn.once('error', (err) => {
        callback(err);
    });
    conn.once('connected', () => {
        callback(null, conn);
    });
}, (err, dbs) => {
    //If a error happenned, it will callback immediately
    //Else, dbs will now be a array of connections
});

I do not know about the performance for such number of connection though.

Upvotes: 1

Related Questions