【问题标题】:How to dynamically connect to a MongoDB database using Nest.js如何使用 Nest.js 动态连接到 MongoDB 数据库
【发布时间】:2021-09-12 08:30:53
【问题描述】:

我需要为客户应用程序中的每个实体创建一个单独的数据库。 我将根据 到请求来自的子域。 如何实现这一点并使用 nestjs 和 mongoose 动态连接到数据库?

用户服务

async findOneByEmail(email: string, subdomain: string): Promise<User | any> {
    const liveConnections = await Databases.getConnection(subdomain)

    const user = await liveConnections.model(User.name, UserSchema).find()
    // { 'securityInfo.email': email }
    if (!user)
        throw new HttpException(
            {
                status: HttpStatus.BAD_REQUEST,
                error: 'user not found',
                field: 'user',
            },
            HttpStatus.BAD_REQUEST
        )

    return user
}

我创建的类
class DataBases extends Mongoose {
    private clientOption = {
        keepAlive: true,
        useNewUrlParser: true,
        useUnifiedTopology: true,
    }

    private databases: { [key: string]: Connection } = {}

    private getConnectionUri = (companyName = '') =>
        `mongodb+srv://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@cluster0.2lukt.mongodb.net/${companyName}?retryWrites=true&w=majority`

    public async getConnection(companyName = ''): Promise<Connection> {
        const connection = this.databases[companyName]
        return connection ? connection : await this.createDataBase(companyName)
    }

    private async createDataBase(comapnyName = ''): Promise<Connection> {
        //  create new connection and if the database not exists just create new one
        const newConnection = await this.createConnection(
            this.getConnectionUri(comapnyName),
            this.clientOption
        )
        this.databases[comapnyName] = newConnection
        return newConnection
    }
}



 

【问题讨论】:

    标签: javascript typescript mongodb nestjs multi-tenant


    【解决方案1】:

    我修好了。我创建的数据库类真的很棒,如果你知道更好的方法,请告诉我。 我必须改变的是我使用与 MongoDB 的连接的方式。 现在我可以连接到不同的数据库,具体取决于子域。

    希望对大家有所帮助!

    用户服务

    async findOneByEmail(email: string, subdomain: string): Promise<User | any> {
        const liveConnections = await Databases.getConnection(subdomain)
        const user = await liveConnections
            .model(User.name, UserSchema)
            .findOne({ 'securityInfo.email': email })
            .exec()
        if (!user)
            throw new HttpException(
                {
                    status: HttpStatus.BAD_REQUEST,
                    error: 'user not found',
                    field: 'user',
                },
                HttpStatus.BAD_REQUEST
            )
    
        return user
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-18
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 2023-02-12
      • 1970-01-01
      相关资源
      最近更新 更多