Search code examples
node.jsmongodbmongoosedatabase

Connect multiple mongo db database in node js using mongoose


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.


Solution

  • 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.