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