Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose switching multiple connections

I am using Node.Js 8.6 along with Mongoose 4.11 and have multiple database connections. Db connections are established via mongoose.createConnection. I found out that mongoose object has connections property (array), where I can see established connections. My question is, what is the proper way, to switch between connections when creating db models in separate modules.

index.js

async function db1() {
    await mongoose.createConnection(
        process.env.MONGODB_URI_1,
        { useMongoClient: true }
    );
}

async function db2() {
    await mongoose.createConnection(
        process.env.MONGODB_URI_2,
        { useMongoClient: true }
    );
}

model.js

//connect to db1

const Test1 = mongoose.model('Test1', new mongoose.Schema({ name: String }));

//connect to db2

const Test2 = mongoose.model('Test2', new mongoose.Schema({ name: String }));
like image 714
Erik Drobne Avatar asked Oct 27 '25 14:10

Erik Drobne


2 Answers

You can use the object return by createConnection in order to handle your multiple connections.

const db1Link = await mongoose.createConnection(
    process.env.MONGODB_URI_1,
    { useMongoClient: true }
);

// Connect to db1
db1Link.model('Test1', new mongoose.Schema({ name: String }));

const db2Link = await mongoose.createConnection(
    process.env.MONGODB_URI_2,
    { useMongoClient: true }
);

// Connect to db2
db2Link.model('Test2', new mongoose.Schema({ name: String }));

Here is what the documentation says about it

Multiple connections

So far we've seen how to connect to MongoDB using Mongoose's default connection. At times we may need multiple connections open to Mongo, each with different read/write settings, or maybe just to different databases for example. In these cases we can utilize mongoose.createConnection() which accepts all the arguments already discussed and returns a fresh connection for you.

var conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options);

This connection object is then used to create and retrieve models. Models are always scoped to a single connection.

like image 95
Orelsanpls Avatar answered Oct 29 '25 04:10

Orelsanpls


//config.json

   {
    "Tenants": {
            "5c061f432c9e9e499325b": {
                "dbConfig": "mongodb://admin:Password@IP/DBname",
                "dbName": "DBname",

            },
            "5c0432ebabb6c9e9e499325b": {
                "dbConfig": "mongodb://admin:Password@IP/DBname",
                "dbName": "DBname",

            },
            "5c061f43bb6c9e9e499325b": {
                "dbConfig": "mongodb://admin:Password@IP/DBname",
                "dbName": "DBname",

            }
        },

    }

//ModelFactory.js

var mongoose = require("mongoose");
var models = [];
var conns = [];
var path = __dirname + "\\models";
var config = require("config");


function factory(tenant) {
    let dbName = config.get("Tenants." + tenant + ".dbName");
    let dbConnection = config.ge`enter code here`t("Tenants." + tenant + ".dbConfig");
    if (conns[dbName]) {
    } else {
        conns[dbName] = mongoose.createConnection(dbConnection);
    }
    if (models[dbName]) {
    } else {
        var instanceModels = [];
        var schemas = ["users","products"];
        schemas.forEach(function (models) {
            instanceModels[models] = conns[dbName].model(models, require([path, models].join("\\")));
        });
        // DB name and tenant ID also pushing in the same object
        //instanceModels["tenantID"] = tenant; 
        //instanceModels["db"] = conns[dbName];
        models[dbName] = instanceModels;        
    }
    return models[dbName];
}
module.exports = factory;

//API End point

exports.users = function (req, res) {

var models = modelFactory(req.headers.tenantid);
models.User.find() //query
like image 44
Jerin K Alexander Avatar answered Oct 29 '25 04:10

Jerin K Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!