如何在NestJS中配置Mongoose连接参数对接AWS DocumentDB
在NestJS中配置Mongoose连接参数(适配AWS DocumentDB)
你只需在MongooseModule.forRootAsync的useFactory返回的配置对象中,直接添加原生Mongoose的连接参数即可——NestJS的Mongoose配置完全兼容原生的连接选项。
修改后的DatabaseModule代码如下:
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { ConfigService } from '@nestjs/config'; import * as path from 'path'; // 引入path模块处理证书路径 @Module({ imports: [ MongooseModule.forRootAsync({ useFactory: async (configService: ConfigService) => ({ uri: configService.get('MONGODB_URI'), // 添加上原生Mongoose的连接参数 readPreference: 'primary', tls: true, tlsAllowInvalidHostnames: true, // 用path.resolve获取证书绝对路径,避免环境路径差异导致的文件找不到问题 tlsCAFile: path.resolve(__dirname, 'rds-combined-ca-bundle.pem'), }), inject: [ConfigService], }), ], }) export class DatabaseModule { static forFeature(models: ModelDefinition[]) { return MongooseModule.forFeature(models); } }
补充说明:
tlsCAFile使用绝对路径更稳妥:通过path.resolve结合__dirname,能确保在不同运行环境下都能定位到证书文件,避免相对路径引发的错误。- 所有配置参数和原生Mongoose的
connect选项完全一致,你可以根据AWS DocumentDB的要求,继续添加其他原生支持的配置项。
内容的提问来源于stack exchange,提问作者Mohammad
相关产品推荐
相关产品推荐

