Multi tenant application using Typescript, Express and MongoDB

Prince Francis
1 min readJun 3, 2020

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/';mongoose.connect(this.mongoUrl, {   useNewUrlParser: true,});

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) {const collegeName = req.get('COLLEGE_NAME');const Student = StudentModel.createModel(collegeName, '2020');let newStudent = new Student(req.body);newStudent.save((err, student) => {if (err) {res.send(err);}res.json(student);});}

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.

https://github.com/princekf/multi-tenant-app-typescript-express-mongodb

--

--