'How to validate mongo connection string in nestjs
I have this MongoDataServicesModule:
@Module({
imports: [
MongooseModule.forFeature([{ name: CatModel.name, schema: UrlSchema }]),
ConfigModule.forRoot(),
MongooseModule.forRoot(process.env.MONGO_CONNECTION_STRING),
],
providers: [{ provide: IDataServices, useClass: MongoDataServices }],
exports: [IDataServices],
})
export class MongoDataServicesModule {}
What I would like to do is validate the connection string.
I used a little bit different layout in my old projects but now I decided to give another one a try and it got me thinking of how to do validation here the right way.
Solution 1:[1]
You can validate it inside useFacatory method - Here is a simple example of how to validate -
MongooseModule.forRootAsync({
useFactory: () => {
let mongoConnectionString = '';
try {
const args = process.argv.slice(2)[0];
mongoConnectionString = args.split('--db=')[1];
} catch (error) {
console.error(
'error fetching mongoDB string from args, should be passed --db=mongodb://localhost:27017/nextgen-promo',
error,
);
process.exit(1);
}
console.log(`connecting to database: ${mongoConnectionString}`);
return { uri: mongoConnectionString };
},
}),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | avi siboni |
