@notross/mongo-singleton
Version:
A lightweight, zero-fuss way to get a single shared MongoDB connection across your Node.js codebase.
123 lines (89 loc) β’ 2.9 kB
Markdown
A lightweight, zero-fuss way to get a **single shared MongoDB connection** across your Node.js codebase. Like me, itβs single and looking for a connection. π
```bash
npm install @notross/mongo-singleton
yarn add @notross/mongo-singleton
```
```typescript
// database.ts
import MongoSingleton from '@notross/mongo-singleton';
const mongoURI = 'mongodb://username:password@localhost:27017';
const databaseName = 'admin';
export const mongoClient = new MongoSingleton(mongoURI, databaseName);
```
Then, in other files:
```typescript
// account.ts
import { mongoClient } from './database';
async function getAccountById(_id: ObjectId) {
const { database } = await mongoClient.connect();
return database.collection('accounts').findOne({ _id });
}
```
> Note:
> - Calling `connect()` multiple times reuses the same connection.
> - Export your MongoSingleton instance to maintain a single shared connection.
Keeps connection logic centralized:
```typescript
/** database.ts */
import MongoSingleton from '@notross/mongo-singleton';
export const mongoClient = new MongoSingleton(
'mongodb://username:password@localhost:27017',
'admin'
);
```
```typescript
/** account.ts */
import { mongoClient } from './database';
export async function getAccountById(_id: ObjectId) {
const { database } = await mongoClient.connect();
return database.collection('accounts').findOne({ _id });
}
```
If you prefer an inline callback approach:
```typescript
const account = await mongoClient.connect(async ({ database }) => {
return database.collection('accounts').findOne({ _id });
});
```
```typescript
let client: MongoClient | null = null;
let database: Db | null = null;
mongoClient.connect().then(({ client: c, database: db }) => {
client = c;
database = db;
});
```
`new MongoSingleton(connectionProps, databaseName)`
- connectionProps can be:
- ConnectionProps β full connection details (host, username, etc.)
- SparseConnectionProps β a MongoDB URI and some config options
- string β just a MongoDB URI
- databaseName: The DB name to use for db.collection() calls.
`.connect(): Promise<{ client: MongoClient; database: Db }>`
- Connects to MongoDB if not already connected.
- Returns the existing connection if one is already open.
`.disconnect(): Promise<void>`
- Closes the connection and resets internal state.
- β
Ensures a single shared connection
- β
Optional built-in logging with configurable log levels
- β
TypeScript support out of the box
```typescript
enum LogLevel {
'debug' = 'debug',
'error' = 'error',
'info' = 'info',
'log' = 'log',
'warn' = 'warn',
}
```