-1

I have the need to dynamically create mongo databases when a new user is registered on a SaaS platform.

How do I configure NestJS to run the scripts needed, to create the database, as well as how to dynamically connect with database created for each user?

And are there any better approaches to my usecase?

New User => Create New Database for them, and store details in the main SaaS database.

When user login, fetch DB details from main database, and create a connection to it, to read their data.

2 Answers2

0

I don't see the need to create a new db for each user. Why not craeting a users collection and than for each user create a new object. Mongo object can store quite a lot of information.

I'm not a pro in nestjs, but I don't think that there is a way to dynamically connect more db's. When you start your app a mongoDB instance is initiated, don't forget that all classes in nestjs are singletones.

Stefan Drl
  • 53
  • 7
0

So, I was able to make it thus.

I created a database service class, in it, I used the MongooseModuleOptions to create a new connection, and injecting the Request Scope to it, I extracted the database name from the request and dynamically pass it to the uri in the createMongooseOptions method and that dynamically creates a connection.

import { Inject } from '@nestjs/common';
import { MongooseOptionsFactory, MongooseModuleOptions } from '@nestjs/mongoose';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';


export class DatabaseService implements MongooseOptionsFactory{
    constructor(
        @Inject(REQUEST) private readonly request: Request) {
    }

    createMongooseOptions(): MongooseModuleOptions {
        const urii = process.env.CLUSTER+'/'+this.request.body.dbName+"?retryWrites=true&w=majority"
        return {
            uri: urii
        };
    }  
}

Then inside the users module, I insert data into a collection specified inside the schema, and that automatically uses the connection to create a database, collection and entry, if it exists, it uses the database and collection.

import { Inject, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { User, UserDocument } from './schemas/user.schema';
import { InjectConnection, InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class UserService {
  constructor(@InjectModel(User.name) private userModel:Model<UserDocument>){}
  
  async create(createUserDto: CreateUserDto) {
    const createdUser = new this.userModel(createUserDto)
    return createdUser.save()
  }

}

That worked perfectly for me.

Thank you all

Dharman
  • 30,962
  • 25
  • 85
  • 135