@edirect/mongo
v11.0.54
Published
> NestJS global module for MongoDB connections with Mongoose, including AWS IAM (IRSA) authentication support.
Maintainers
Keywords
Readme
@edirect/mongo
NestJS global module for MongoDB connections with Mongoose, including AWS IAM (IRSA) authentication support.
This package provides a plug-and-play NestJS module that manages a Mongoose connection to MongoDB. It reads connection configuration from the environment via @edirect/config, automatically applies AWS IAM credential rotation when the MONGODB-AWS auth mechanism is detected, and tunes connection-pool settings for non-production environments. The resulting Mongoose instance is exposed under the MONGO_CONNECTION injection token and is available globally across the application.
Features
- Single-import global NestJS module (
MongoModule) - Automatic AWS IAM / IRSA credential rotation via
@aws-sdk/credential-providers - Supports both
MONGO_URLandMONGODB_URIenvironment variables (priority:MONGO_URL) - Conservative connection-pool defaults for development and test environments
getConnectionutility for building connection parameters outside NestJS DIMONGO_CONNECTIONinjection token for directMongooseinstance injection
Installation
npm install @edirect/mongoConfiguration
Environment Variables
| Variable | Type | Default | Description |
| ----------------------------- | -------- | ------- | ---------------------------------------------------------------------------------- |
| MONGO_URL | string | — | Primary MongoDB connection string (takes precedence over MONGODB_URI). |
| MONGODB_URI | string | — | Fallback MongoDB connection string. |
| NODE_ENV | string | — | Runtime environment. When production or live, pool tuning is disabled. |
| MONGODB_AWS_ROLE_ARN | string | — | AWS IAM auth only. ARN of the IAM role to assume via STS. |
| AWS_WEB_IDENTITY_TOKEN_FILE | string | — | AWS IAM auth only. Path to the Kubernetes service-account token file for IRSA. |
At least one of
MONGO_URLorMONGODB_URImust be set, or the module will throw at startup.
Usage
Basic Setup
// app.module.ts
import { Module } from '@nestjs/common';
import { MongoModule } from '@edirect/mongo';
@Module({
imports: [MongoModule],
})
export class AppModule {}Injecting the Mongoose Connection
Use the MONGO_CONNECTION token to inject the raw Mongoose instance anywhere in your application:
import { Injectable, Inject } from '@nestjs/common';
import { MONGO_CONNECTION } from '@edirect/mongo';
import mongoose from 'mongoose';
@Injectable()
export class DatabaseService {
constructor(
@Inject(MONGO_CONNECTION) private readonly connection: mongoose.Mongoose
) {}
isConnected(): boolean {
return this.connection.connection.readyState === 1;
}
}Registering Mongoose Models
After importing MongoModule, register your schemas as model providers in feature modules:
import { Module } from '@nestjs/common';
import { getModelToken } from 'mongoose';
import { MONGO_CONNECTION } from '@edirect/mongo';
import { PolicySchema } from './policy.schema';
@Module({
providers: [
{
provide: getModelToken('Policy'),
useFactory: (connection: mongoose.Mongoose) =>
connection.model('Policy', PolicySchema),
inject: [MONGO_CONNECTION],
},
],
exports: [getModelToken('Policy')],
})
export class PolicyModule {}Standard Username/Password Connection
# .production.env
MONGO_URL=mongodb://username:password@mongo-host:27017/mydb?authSource=adminAWS IAM (IRSA/EKS) Connection
For EKS workloads with IRSA enabled, set the following environment variables:
MONGO_URL=mongodb+srv://cluster.example.com/mydb?authMechanism=MONGODB-AWS
MONGODB_AWS_ROLE_ARN=arn:aws:iam::123456789012:role/my-mongo-role
AWS_WEB_IDENTITY_TOKEN_FILE=/var/run/secrets/eks.amazonaws.com/serviceaccount/tokenThe module will automatically rotate credentials using @aws-sdk/credential-providers fromNodeProviderChain.
Using getConnection Programmatically
import { getConnection } from '@edirect/mongo';
import { ConfigService } from '@edirect/config';
const config = new ConfigService();
const connectionParams = getConnection(config);
// Returns mongoose connection parameters object
const connection = await mongoose.createConnection(
connectionParams.uri,
connectionParams.options
);Connection Pool Sizing
The module automatically adjusts pool settings based on NODE_ENV:
| NODE_ENV | Behavior |
| --------------------- | ---------------------------------------------------- |
| production / live | Default Mongoose pool settings |
| anything else | Conservative pool settings (reduced for development) |
API Reference
MongoModule
A global @Module() with no configuration options. Import it once in your root AppModule.
import { MongoModule } from '@edirect/mongo';getConnection(configService: ConfigService): MongoConnectionParams
Utility function that resolves the MongoDB connection string from ConfigService and returns the connection parameters.
| Parameter | Type | Description |
| --------------- | --------------- | ----------------------------------------------- |
| configService | ConfigService | Instance of @edirect/config's ConfigService |
Returns: Object containing the resolved URI and Mongoose connection options.
Throws: If neither MONGO_URL nor MONGODB_URI is set in the environment.
MONGO_CONNECTION
Injection token (string) for the Mongoose instance. Use with @Inject(MONGO_CONNECTION).
MongoProviders
Array of NestJS providers that wires the MONGO_CONNECTION token. Used internally by MongoModule.
Examples
Complete AppModule with Mongoose Model
// app.module.ts
import { Module } from '@nestjs/common';
import { MongoModule } from '@edirect/mongo';
import { PolicyModule } from './policy/policy.module';
@Module({
imports: [MongoModule, PolicyModule],
})
export class AppModule {}// policy/policy.module.ts
import { Module } from '@nestjs/common';
import mongoose, { Schema } from 'mongoose';
import { MONGO_CONNECTION } from '@edirect/mongo';
import { PolicyService } from './policy.service';
const PolicySchema = new Schema({
policyNumber: String,
premium: Number,
startDate: Date,
});
@Module({
providers: [
{
provide: 'POLICY_MODEL',
useFactory: (conn: mongoose.Mongoose) =>
conn.model('Policy', PolicySchema),
inject: [MONGO_CONNECTION],
},
PolicyService,
],
exports: [PolicyService],
})
export class PolicyModule {}// policy/policy.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { Model } from 'mongoose';
@Injectable()
export class PolicyService {
constructor(
@Inject('POLICY_MODEL') private readonly policyModel: Model<any>
) {}
findAll() {
return this.policyModel.find().exec();
}
}Health Check
import { Injectable, Inject } from '@nestjs/common';
import { MONGO_CONNECTION } from '@edirect/mongo';
import mongoose from 'mongoose';
@Injectable()
export class HealthService {
constructor(
@Inject(MONGO_CONNECTION) private readonly mongo: mongoose.Mongoose
) {}
isHealthy(): boolean {
// readyState: 0=disconnected, 1=connected, 2=connecting, 3=disconnecting
return this.mongo.connection.readyState === 1;
}
}