2

What I want to do is to use different databases for different users, for example I have 3 users that would connect to:

www.user1.myfrontend.com

www.user2.myfrontend.com

www.user3.myfrontend.com

Let's suppose that each user want to display the list of products he has, a GET request would be sent to the backend and from there I will connect to the database of the user:

mongodb://mongodatabse:secret@server/databaseOfUser1 mongodb://mongodatabse:secret@server/databaseOfUser2 mongodb://mongodatabse:secret@server/databaseOfUser3

What I did so far:

I connect to the database called config at the start of the app:

db.js

const connect = (uri, app, database="config") => {
   const db= mongoose
        .createConnection(uri,{ useNewUrlParser: true, useUnifiedTopology: true })
    db.on('open', () => {
        mongoose.connection.useDb("config")
        app.emit('dbReady');
        return true;
    });

    db.on('error', (err) => {
        console.log(`Couldn't connect to database': ${err.message}`);
        return false;
    });
};

server.js

db.connect(process.env.MONGODB_URL, app);
app.on('dbReady', function () {
    server.listen(PORT, () => {
        console.info(`> Frontend is hosted @: ${process.env.BASE_URL}`);
        console.info(`> Database is hosted @: ${process.env.mongodb_url}`);
        console.info(`> Listening on port ${PORT}`);
    });
});

Then whenever I receive a request I check in the config database for the database to use:

app.js:

const AccessConfig = require('./models/schemas/AccessConfigSchema');
const db = require('./models/db');
app.use(async (req, res, next) => {
    const subdomain = req.subdomains[req.subdomains.length - 1];
    try {
        let database = await AccessConfig.findOne({ subdomain: subdomain});
        if (!database)
            database= await AccessConfig.findOne({ subdomain: "demo"});
        console.log(database);
        db.useDb(database);
        next();
    } catch (e) {
        console.log(e.message)
        return res.status(500).send('Error: ' + e.message);
    }

});

So far It seems like the database isn't changing and I'm not even sure that this is the correct implementation or too many connections are open, etc.

MSOS
  • 21
  • 1
  • MongoDB will use the database name 'config' for sharding data if you ever get big enough to need sharding, so choosing a different name for the DB now will prevent problems if your application ever gets that big. – Joe Jan 04 '23 at 09:54
  • Seems to be a duplicate question https://stackoverflow.com/questions/19474712/mongoose-and-multiple-database-in-single-node-js-project – Sardar Jan 12 '23 at 12:49

1 Answers1

1

I figured out, you can create connections using

//DB_URI_USER1=mongodb://mongodatabse:secret@server/databaseOfUser1 

//DB_URI_USER2=mongodb://mongodatabse:secret@server/databaseOfUser2

   const user1Connection = mongoose.createConnection(process.env.DB_URI_USER1, {
       useNewUrlParser: true,
       useUnifiedTopology: true,
   })

   const user2Connection = mongoose.createConnection(process.env.DB_URI_USER2, {
       useNewUrlParser: true,
       useUnifiedTopology: true,
   })

Then you create the model for each

const User1 = user1Connection.model(...)
const User2 = user2Connection.model(...)

Now on the API you query the desired model.

Working for me :)

Maxiim3
  • 31
  • 5
  • I also implemented a similar kind of implementation with mongoose 5. But useDb() method work for me. In mongoose 7 it doesn't work. Now I'm planning to move towards a implementation like yours in mongoose 7. How many databases have you planned for approximately? – Md.Reyad Hossain Apr 28 '23 at 13:26
  • Now I get an error saying schema._clone is not a function – Md.Reyad Hossain Apr 28 '23 at 13:34
  • "How many databases have you planned for approximately?" - What do you mean ? "Now I get an error saying schema._clone is not a function" - I am not that advanced with mongoose or mongodb... – Maxiim3 May 09 '23 at 15:36
  • 'schema._clone' it turned out to be a version related error which I found the solution. But In my other question "How many databases have you planned for approximately" I wanted to know how many databases will u have as your system scales? Because every user signing up will have new db in your system. So apparently I wanted to know how many user databases will be there in your system? – Md.Reyad Hossain May 10 '23 at 16:18