Home > Mobile >  Nest JS combine plugins and configurations for DB
Nest JS combine plugins and configurations for DB

Time:10-06

How Can I combine the 2 recipes below? Or what would be the ideal script for this?

1. Mongoose plugins using connection factory for all schemas https://docs.nestjs.com/techniques/mongodb#plugins

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

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/test', {
      connectionFactory: (connection) => {
        connection.plugin(require('mongoose-autopopulate'));
        return connection;
      }
    }),
  ],
})
export class AppModule {}

2. Database configuration using NestJS Config Module https://docs.nestjs.com/techniques/configuration

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
    }),
    MongooseModule.forRootAsync({
      inject: [ConfigService],
      imports: [ConfigModule],
      useFactory: (config: ConfigService) => ({ uri: config.get<string>('database') })
    })
  ]
})
export class AppModule { }

CodePudding user response:

Something like the following should work. useFactory is expected to return the same object that forRoot accepts (or a promise that resolves to the same object), so you should be able to copy/paste any options between the two.

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
    }),
    MongooseModule.forRootAsync({
      inject: [ConfigService],
      imports: [ConfigModule],
      useFactory: (config: ConfigService) => ({ 
        uri: config.get<string>('database'),
        connectionFactory: (connection) => {
          connection.plugin(require('mongoose-autopopulate'));
          return connection;
        }
      })
    })
  ]
})
export class AppModule { }
  • Related