Search code examples
node.jstypescriptbackendadonis.jslucid

AdonisJS 5, dynamically connect database


Hi used Adonis Js 5 with the new version. I have multiple database clients with the same database structure, can I create a new database connection without declaring the config at config/database.ts? it means I can create a connection on the fly.


Solution

  • Yes finally I can make it, with this:

    Database.manager.patch(this.database.name, {
      client: 'mysql',
      connection: {
        host: Env.get('DB_HOST'),
        port: Env.get('DB_PORT'),
        user: this.database.username,
        password: this.database.password,
        database: this.database.name,
      },
      debug: Env.get('DB_DEBUG', false),
    })
    Database.manager.connect(this.database.name)