3

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.

6
  • Possible dupe of stackoverflow.com/questions/19474712/… Commented Mar 21, 2017 at 4:10
  • @JohnnyHK I have updated my question. Also the answers provided to the other question do not suffice my needs. Thanks anyways. Commented Mar 23, 2017 at 3: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. Commented Mar 23, 2017 at 14:32
  • Possible duplicate of Mongoose and multiple database in single node.js project Commented Feb 21, 2018 at 1:24
  • @Jalasem - That question refers to 2 DBs in different controllers, I want to implement the same in single controller. Commented Feb 28, 2018 at 14:58

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.