npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@edirect/mongo

v11.0.54

Published

> NestJS global module for MongoDB connections with Mongoose, including AWS IAM (IRSA) authentication support.

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_URL and MONGODB_URI environment variables (priority: MONGO_URL)
  • Conservative connection-pool defaults for development and test environments
  • getConnection utility for building connection parameters outside NestJS DI
  • MONGO_CONNECTION injection token for direct Mongoose instance injection

Installation

npm install @edirect/mongo

Configuration

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_URL or MONGODB_URI must 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=admin

AWS 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/token

The 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;
  }
}