Home > OS >  How can I connect to a MySQL database with custom value?
How can I connect to a MySQL database with custom value?

Time:01-14

I have a NestJs project. There is a connection to different databases that have already been created in advance.

TypeOrmModule.forRoot({
      "type": "mysql",
      "host": "***,
      "port": 3306,
      "username": "***",
      "password": "***",
      "database": "db_name",
      "autoLoadEntities": true,
      "name": "users_db",
      "synchronize": true
    }), 

When user registers, a database is created with his [user_id]. And I need to add data in this db. How can I connect to his database by taking his id? I can't pass data to app.module or is there some other way? I have never worked with typeorm before.

CodePudding user response:

TypeOrm has some docs on this here.

An example from those docs:

const users = await connection
    .createQueryBuilder()
    .select()
    .from("secondDB.user", "user")
    .addFrom("thirdDB.photo", "photo")
    .andWhere("photo.userId = user.id")
    .getMany(); 

This feature is supported only in mysql and mssql databases.

Where secondDB and thirdDB are both different databases within the same connection.

You'll use this almost exactly the same as you normally would in Nest. Set up with .forRoot() in the app module, inject the repository or connection, and then create the query builder.

CodePudding user response:

You can't change if you have one instance your app. If you create for each user separate instance your app it is possible. But why you want change this ?

Use env like here username: process.env.POSTGRES_DB_USERNAME,

But if you want in any entity add whoCreated, whoUpdated you need add just info about logged user to you service update/save.

  •  Tags:  
  • Related