m mohammadi
m mohammadi

Reputation: 21

Error connecting to the database in NestJs

In nestJs, I want to connect to two databases, I have a problem I have two separate databases, each of which stores a series of data in themselves, both are mysql, but when I define the entities, it gives an error that it cannot recognize both databases.

 imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'password',
      database: 'users_db',
      entities: [__dirname + '//*.entity{.ts,.js}'],
      synchronize: true,
    }),
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'password',
      database: 'products_db',
      entities: [__dirname + '//*.entity{.ts,.js}'],
      synchronize: true,
    }),
    UsersModule,
    ProductsModule,
  ],```

This is the error I have

EntityMetadataNotFoundError: No metadata for "Product" was found

Upvotes: 1

Views: 31

Answers (1)

Jonathan
Jonathan

Reputation: 1

If you wanna connect 2 diffrent databases in nestjs you need to do it like this:

    imports: [
    TypeOrmModule.forRoot({
      name: 'default',
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'password',
      database: 'users_db',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
    }),
    TypeOrmModule.forRootAsync({
      name: 'productsConnection',
      useFactory: () => ({
        type: 'mysql',
        host: 'localhost',
        port: 3306,
        username: 'root',
        password: 'password',
        database: 'products_db',
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: true,
      }),
    }),
    UsersModule,
    ProductsModule,
  ],

and if you wanna use them import them like:

TypeOrmModule.forFeature([YourEntity], 'productsConnection')

Upvotes: 0

Related Questions