How to connect to different database according to request in node js and mongoose

Viewed 111

I am developing a SaaS application with multiple users. So I need to use appropriate database according to requesting user. Below is my basic database connection.

mongoose.connect(databaseLink, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true
})

We can use createConnection instead of connect to connect to multiple database. But for that I need to specify separate models. Here I need to share same model for each databases.

Edit

You can assume that required database name will be stored in req.dbName object. So when a user make a request from client1, req.dbName will equals to client1 and I need to use client1 database for that particular request.

2 Answers

you can simply make an object and store all connection strings there and as per the need you can use the connection string

var connetion_string = { "user":"mongodb://localhost:27017/usercollection", "marks":"mongodb://localhost:27017/markscollection"

}

Related