Multi tenant application using Typescript, Express and MongoDB

Let us create a multiple database application (multi tenant application)

Mutli tenant application structure.

Problem : Create an application to manage schools and colleges. Each school/college data should save in separate database. Also students in each years should save in separate collections.

I solved these problem by using `mongoose.connection.useDb` method and using collection_name parameter while creating the model.

Initial mongo setup is same, connect to a mongo db using mongoose.

public mongoUrl: string = 'mongodb://localhost/';

We do the trick in the model class

In the controller we call the createModel method with 2 parameters college_name as db name prefix and year as collection name prefix.

In the controller file, we receive COLLEGE_NAME from request header. It should be from session in real scenario.

public addNewStudent(req: Request, res: Response) {

The Database and collection names are decided on the request call only. So we can store the data into different database as per the user session.

You could refer the following github repository for an example.

Providing simple solutions for complex problems.