site logo

Marico' space

nest.js + mongodb useFactory 连接数据库

Others 2024-08-16 22:32:33 380

近日拿nest+mongodb做点小测试, 忽然发现官方文档里给的是直接的连接, 就想着,是不是也可用·useFactory·,实现用CnfigService获取数据库URI,来连接数据库。

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';

@Module({
  imports: [MongooseModule.forRoot('mongodb://localhost/nest')],
})
export class AppModule {}

于是多方查询下,测试成功。遂将方案分享余下:

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigService } from '@/modules/shared/config/config.service';
import { SharedModule } from '@/modules/shared/shared.module';

@Module({
  imports: [
    MongooseModule.forRootAsync({
      imports: [SharedModule],
      inject: [ConfigService],
      useFactory: (configService) => ({
        uri: configService.dbUri,
        useNewUrlParser: true,
        useUnifiedTopology: true,
      }),
    }),
  ],
})
export class DatabaseModule {}