2

I am using mongoose for mongo db connections in node js. Can anyone tell me how can I connect multiple databases in node js. Also please make sure that you have tried that method yourself. Thanks.

Edit: I want to connect to multiple DBs dynamically. Also I don't want multiple models and I have just one project, not various sub-projects.

Community
  • 1
  • 1
  • Possible dupe of https://stackoverflow.com/questions/19474712/mongoose-and-multiple-database-in-single-node-js-project – JohnnyHK Mar 21 '17 at 04:10
  • @JohnnyHK I have updated my question. Also the answers provided to the other question do not suffice my needs. Thanks anyways. – Ashish Sherashia Mar 23 '17 at 03:36
  • You need to add a lot more specifics to your question. Show the connection code that you have so far that illustrates what you're trying to do and what's not working about it. – JohnnyHK Mar 23 '17 at 14:32
  • Possible duplicate of [Mongoose and multiple database in single node.js project](https://stackoverflow.com/questions/19474712/mongoose-and-multiple-database-in-single-node-js-project) – Jalasem Feb 21 '18 at 01:24
  • @Jalasem - That question refers to 2 DBs in different controllers, I want to implement the same in single controller. – Ashish Sherashia Feb 28 '18 at 14:58
  • the accepted answer still apply to your problem – Jalasem Mar 02 '18 at 06:01

2 Answers2

3

i believe you are connecting to mongoDB from main entrypoint as index.js or server.js , where you are initiating router. like this `

    const mongoose = require('mongoose')
    // mongoose
    mongoose.connect("mongoDB url");
    const connection = mongoose.connection;
    connection.on('open',()=>{
        console.log(" database connected")
    })
    connection.on('error',()=>{
        console.log("error in connecting to database")
    })
    app.use(morgan('dev'));
    app.use(bodyParser.urlencoded({extended: false}));
    app.use(bodyParser.json());
    //middlewares`

in same way you can also connect to different databases directly schemas. like in my use case , i wanted to store users in defferent database and posts in another DB . the in my app.js , i will connect to main DB as normal connection (above) and for user schema , i will connect to my user DB . like this

    const mongoose = require('mongoose');
    const connection = mongoose.createConnection("mongo url ");
    const userSchema = mongoose.Schema({
       name: String,
       date_of_birth: Date
      })
    module.exports = mongoose.model('User', userSchema);

you can also use mongoose.connect() instead of mongoose.createConnection()

hope this helped you.

vamshi krishna
  • 2,618
  • 1
  • 11
  • 18
0
const mongoose = require('mongoose');
require('dotenv').config()



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

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

    db.on('connected', function () {
        console.log(`MongoDB :: connected ${this.name} - ${new Date().toISOString()}`);
    });

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

    return db;
}


const db_charge_config = process.env.DB_HOST_RECHARGE;
const db_log_config = process.env.DB_HOST;


const Connection_db_charge = makeNewConnection(db_charge_config);
const connection_db_log = makeNewConnection(db_log_config);

module.exports = {
    Connection_db_charge,
    connection_db_log
};`enter code here`