Promise-based MongoDB connection helper using mongoose with configurable read preference
npm install @tamasha/mongo-connectionPromise-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.
``bash`
npm install @tamasha/mongo-connection
> Requires Node.js 18+ and MongoDB 4.4+.
`ts
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);
});
`
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. |
Gracefully closes the current connection and resets the singleton.
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.
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.
1. Add @tamasha/mongo-connection to your project.disconnectMongo()
2. Initialize the connection during application bootstrap (before defining models or starting HTTP servers).
3. Use your mongoose models as usual—the helper ensures the underlying connection is ready and shared across the app.
4. During shutdown, call (e.g. on SIGTERM / SIGINT`) to close connections cleanly.
This keeps connection logic clean and consistent across multiple services.