@tamasha/mongo-connection
v1.0.0
Published
Promise-based MongoDB connection helper using mongoose with configurable read preference
Readme
@tamasha/mongo-connection
Promise-based MongoDB connection helper built on top of mongoose. It keeps a singleton connection, exposes lifecycle logs, and lets you configure the readPreference (and other mongoose options) per project.
Installation
npm install @tamasha/mongo-connectionRequires Node.js 18+ and MongoDB 4.4+.
Quick Start
import { mongoDbConnection } from "@tamasha/mongo-connection";
async function bootstrap() {
await mongoDbConnection({
uri: process.env.MONGODB_CONNECTION_URL,
readPreference: "secondaryPreferred",
autoIndex: false,
});
// Your mongoose models can be registered here
}
bootstrap().catch((error) => {
console.error("Failed to start application:", error);
process.exit(1);
});API
mongoDbConnection(options?: MongoDbConnectionOptions): Promise<typeof mongoose>
Creates (or reuses) a singleton connection. The promise resolves once the connection is ready. Subsequent calls reuse the same connection.
| Option | Type | Description |
|--------|------|-------------|
| uri | string | Connection string. Defaults to process.env.MONGODB_CONNECTION_URL. |
| readPreference | ConnectOptions["readPreference"] | Preferred read preference. Defaults to "secondaryPreferred". |
| autoIndex | boolean | Enable or disable automatic index building. Defaults to false. |
| options | ConnectOptions | Additional mongoose.connect options. |
| reconnectOnDisconnect | boolean | Auto-reconnect if the connection drops. Defaults to true. |
disconnectMongo(): Promise<void>
Gracefully closes the current connection and resets the singleton.
Connection Events
The package logs key connection events: connecting, connected, open, error, disconnected, and reconnected. When reconnectOnDisconnect is enabled, the package will automatically retry connection attempts using the provided configuration.
Real-World Usage Example
See examples/usage.ts for a complete walkthrough, including:
- Setting up the connection with environment variables.
- Registering models and running queries.
- Gracefully shutting down on process signals.
External Project Integration
- Add
@tamasha/mongo-connectionto your project. - Initialize the connection during application bootstrap (before defining models or starting HTTP servers).
- Use your mongoose models as usual—the helper ensures the underlying connection is ready and shared across the app.
- During shutdown, call
disconnectMongo()(e.g. onSIGTERM/SIGINT) to close connections cleanly.
This keeps connection logic clean and consistent across multiple services.
