{"id":18435736,"url":"https://github.com/kisiwu/storehouse-mongodb","last_synced_at":"2026-05-03T17:33:59.828Z","repository":{"id":57163034,"uuid":"391326075","full_name":"kisiwu/storehouse-mongodb","owner":"kisiwu","description":"MongoDB driver manager for @storehouse/core.","archived":false,"fork":false,"pushed_at":"2024-03-03T12:57:33.000Z","size":84,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-03-21T07:35:49.194Z","etag":null,"topics":["database","mongodb","nodejs"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kisiwu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-07-31T10:38:22.000Z","updated_at":"2023-08-14T14:53:02.000Z","dependencies_parsed_at":"2024-03-03T13:53:32.676Z","dependency_job_id":null,"html_url":"https://github.com/kisiwu/storehouse-mongodb","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kisiwu%2Fstorehouse-mongodb","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kisiwu%2Fstorehouse-mongodb/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kisiwu%2Fstorehouse-mongodb/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kisiwu%2Fstorehouse-mongodb/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kisiwu","download_url":"https://codeload.github.com/kisiwu/storehouse-mongodb/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248866739,"owners_count":21174593,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","mongodb","nodejs"],"created_at":"2024-11-06T06:09:12.183Z","updated_at":"2026-05-03T17:33:59.822Z","avatar_url":"https://github.com/kisiwu.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# @storehouse/mongodb\n\nMongoDB driver manager adapter for [@storehouse/core](https://www.npmjs.com/package/@storehouse/core). Provides seamless integration with [MongoDB](https://www.mongodb.com/) using the official [Node.js driver](https://www.npmjs.com/package/mongodb).\n\n## Features\n\n- **Type-safe MongoDB operations** with TypeScript support\n- **Connection lifecycle management** with automatic event logging\n- **Health check utilities** for monitoring (works without admin privileges)\n- **Multi-manager support** via Storehouse registry\n- **Cross-database access** using dot notation\n\n## Prerequisites\n\n- **MongoDB server**\n- **Node.js** 18 or higher\n\n## Installation\n\n```bash\nnpm install @storehouse/core mongodb @storehouse/mongodb\n```\n\n## Quick Start\n\n### 1. Define Your Types\n\n**models/movie.ts**\n```ts\nexport interface Movie {\n  title: string;\n  director: string;\n  year: number;\n  rating?: number;\n}\n```\n\n### 2. Register the Manager\n\n**index.ts**\n```ts\nimport { Storehouse } from '@storehouse/core';\nimport { MongoDbManager } from '@storehouse/mongodb';\n\n// Register the manager\nStorehouse.add({\n  mongodb: {\n    type: MongoDbManager,\n    config: {\n      url: 'mongodb://localhost:27017/mydb',\n      // MongoClientOptions\n      options: {\n        maxPoolSize: 10,\n        minPoolSize: 5\n      }\n    }\n  }\n});\n```\n\n### 3. Connect and Use\n\n```ts\nimport { Storehouse } from '@storehouse/core';\nimport { MongoDbManager } from '@storehouse/mongodb';\nimport { Collection, MongoClient } from 'mongodb';\nimport { Movie } from './models/movie';\n\n// Get the manager and connect\nconst manager = Storehouse.getManager\u003cMongoDbManager\u003e('mongodb');\n\nif (manager) {\n  // Open the connection\n  await manager.connect();\n  \n  console.log('Connected to database:', manager.db().databaseName);\n  \n  // Get a collection\n  const moviesCollection = manager.getModel\u003cMovie\u003e('movies');\n  \n  // Insert a document\n  await moviesCollection.insertOne({\n    title: 'Sinners',\n    director: 'Ryan Coogler',\n    year: 2025,\n    rating: 8.5\n  });\n  \n  // Query documents\n  const movies = await moviesCollection.find({ year: { $gte: 2010 } }).toArray();\n  console.log('Movies:', movies);\n  \n  // Count documents\n  const count = await moviesCollection.countDocuments();\n  console.log('Total movies:', count);\n}\n```\n\n## API Reference\n\n### Helper Functions\n\nThe package provides helper functions that throw errors instead of returning undefined, making your code cleaner and safer.\n\n#### `getManager()`\n\nRetrieves a MongoDbManager instance from the registry.\n\n```ts\nimport { Storehouse } from '@storehouse/core';\nimport { getManager } from '@storehouse/mongodb';\n\nconst manager = getManager(Storehouse, 'mongodb');\nawait manager.connect();\n```\n\n**Throws:**\n- `ManagerNotFoundError` - If the manager doesn't exist\n- `InvalidManagerConfigError` - If the manager is not a MongoDbManager instance\n\n#### `getConnection()`\n\nRetrieves the underlying MongoDB client connection.\n\n```ts\nimport { Storehouse } from '@storehouse/core';\nimport { getConnection } from '@storehouse/mongodb';\n\nconst client = getConnection(Storehouse, 'mongodb');\nawait client.connect();\n\n// Access the database\nconst db = client.db('mydb');\nconst collections = await db.listCollections().toArray();\n```\n\n**Throws:**\n- `ManagerNotFoundError` - If the manager doesn't exist\n- `InvalidManagerConfigError` - If the manager is not a MongoClient instance\n\n#### `getModel()`\n\nRetrieves a MongoDB Collection by name.\n\n```ts\nimport { Storehouse } from '@storehouse/core';\nimport { getModel } from '@storehouse/mongodb';\nimport { Movie } from './models/movie';\n\n// Get model from default manager\nconst movies = getModel\u003cMovie\u003e(Storehouse, 'movies');\n\n// Get model from specific manager\nconst users = getModel(Storehouse, 'mongodb', 'users');\n\n// Use the collection\nconst count = await movies.countDocuments();\nconsole.log('Total movies:', count);\n```\n\n**Throws:**\n- `ModelNotFoundError` - If the model doesn't exist\n\n### MongoDbManager Class\n\n#### Methods\n\n##### `connect(): Promise\u003cthis\u003e`\n\nEstablishes connection to MongoDB.\n\n```ts\nawait manager.connect();\n```\n\n##### `close(force?: boolean): Promise\u003cvoid\u003e`\n\nCloses the MongoDB connection.\n\n```ts\n// Graceful close\nawait manager.close();\n\n// Force close\nawait manager.close(true);\n```\n\n##### `closeConnection(force?: boolean): Promise\u003cvoid\u003e`\n\nAlias for `close()`. Closes the MongoDB connection.\n\n```ts\nawait manager.closeConnection();\n```\n\n##### `getConnection(): MongoClient`\n\nReturns the underlying MongoDB client instance.\n\n```ts\nconst client = manager.getConnection();\nconst db = client.db('mydb');\n```\n\n##### `getModel\u003cT\u003e(name: string): Collection\u003cT\u003e`\n\nRetrieves a MongoDB collection by name. Supports dot notation for cross-database access.\n\n```ts\n// Get collection from default database\nconst movies = manager.getModel\u003cMovie\u003e('movies');\n\n// Get collection from specific database\nconst users = manager.getModel('otherdb.users');\n```\n\n##### `isConnected(): Promise\u003cboolean\u003e`\n\nChecks if the connection is currently active. Works without admin privileges.\n\n```ts\nconst connected = await manager.isConnected();\nif (connected) {\n  console.log('MongoDB is connected');\n}\n```\n\n##### `healthCheck(): Promise\u003cMongoDbHealthCheckResult\u003e`\n\nPerforms a comprehensive health check including ping test and latency measurement. Works without admin privileges.\n\n```ts\nconst health = await manager.healthCheck();\n\nif (health.healthy) {\n  console.log(`✓ MongoDB is healthy`);\n  console.log(`  Database: ${health.details.databaseName}`);\n  console.log(`  Latency: ${health.details.latency}`);\n} else {\n  console.error(`✗ MongoDB is unhealthy: ${health.message}`);\n}\n```\n\n### Health Check Result\n\nThe health check returns a detailed result object:\n\n- `healthy: boolean` - Overall health status\n- `message: string` - Descriptive message about the health status\n- `timestamp: number` - Timestamp when the health check was performed\n- `latency?: number` - Response time in milliseconds\n- `details: object` - Detailed connection information\n  - `name: string` - Manager name\n  - `isOpen: boolean` - Connection open status\n  - `isReady: boolean` - Connection ready status\n  - `pingResponse?: Document` - MongoDB ping response\n  - `latency?: string` - Response time in ms\n  - `error?: string` - Error details (if unhealthy)\n\n## Advanced Usage\n\n### Multiple Managers\n\nYou can register multiple MongoDB connections:\n\n```ts\nimport { Storehouse } from '@storehouse/core';\nimport { MongoDbManager, getManager } from '@storehouse/mongodb';\n\nStorehouse.add({\n  primary: {\n    type: MongoDbManager,\n    config: {\n      url: 'mongodb://localhost:27017/maindb'\n    }\n  },\n  analytics: {\n    type: MongoDbManager,\n    config: {\n      url: 'mongodb://localhost:27017/analyticsdb'\n    }\n  }\n});\n\n// Access specific managers\nconst primaryManager = getManager(Storehouse, 'primary');\nconst analyticsManager = getManager(Storehouse, 'analytics');\n```\n\n### Using the Manager Type\n\nSet the manager type to simplify configuration and use string identifiers instead of class references:\n\n```ts\nimport { Storehouse } from '@storehouse/core';\nimport { MongoDbManager } from '@storehouse/mongodb';\n\n// Set default manager type\nStorehouse.setManagerType(MongoDbManager);\n\n// Now you can use type string instead of class\nStorehouse.add({\n  mongodb: {\n    type: '@storehouse/mongodb',\n    config: {\n      url: 'mongodb://localhost:27017/mydb'\n    }\n  }\n});\n```\n\n### Cross-Database Access\n\nAccess collections from different databases sharing the same socket connection using dot notation:\n\n```ts\nimport { Storehouse } from '@storehouse/core';\nimport { getModel } from '@storehouse/mongodb';\n\n// Access collection from another database\nconst otherDbMovies = getModel(Storehouse, 'mongodb', 'otherdatabase.movies');\n\n// Or using Storehouse directly\nconst Movies = Storehouse.getModel('mongodb', 'otherdatabase.movies');\n\n// Query the collection\nconst movies = await otherDbMovies?.find({}).toArray();\n```\n\nThe format is: `\u003cdatabase-name\u003e.\u003ccollection-name\u003e`\n\n### Connection Event Handling\n\nThe manager automatically logs connection lifecycle events. These are logged using the `@novice1/logger` package and can be enabled with Debug mode:\n\n```ts\nimport { Debug } from '@novice1/logger';\n\nDebug.enable('@storehouse/mongodb*');\n```\n\n**Events logged:**\n- `topologyOpening` - Connection initiated\n- `serverOpening` - Server connection established\n- `serverClosed` - Server connection closed\n- `topologyClosed` - Connection closed\n- `error` - Connection errors\n\n## TypeScript Support\n\nThe package is written in TypeScript and provides full type definitions for type-safe operations:\n\n```ts\nimport { Storehouse } from '@storehouse/core';\nimport { MongoClient, Collection } from 'mongodb';\nimport { MongoDbManager, getManager, getConnection, getModel } from '@storehouse/mongodb';\n\n// Typed manager\nconst manager = getManager\u003cMongoDbManager\u003e(Storehouse, 'mongodb');\n\n// Typed connection\nconst client: MongoClient = getConnection(Storehouse, 'mongodb');\n\n// Typed collection with document interface\ninterface User {\n  name: string;\n  email: string;\n  age: number;\n}\n\nconst users = getModel\u003cUser\u003e(Storehouse, 'mongodb', 'users');\n// users is typed as Collection\u003cUser\u003e\n\n// Type-safe operations\nconst allUsers = await users.find({}).toArray();\n// allUsers is typed as User[]\n```\n\n## Error Handling\n\nAll helper functions throw specific errors for better error handling:\n\n```ts\nimport { Storehouse } from '@storehouse/core';\nimport { getManager, getModel, getConnection } from '@storehouse/mongodb';\nimport {\n  ManagerNotFoundError,\n  ModelNotFoundError,\n  InvalidManagerConfigError\n} from '@storehouse/core';\n\ntry {\n  const manager = getManager(Storehouse, 'nonexistent');\n} catch (error) {\n  if (error instanceof ManagerNotFoundError) {\n    console.error('Manager not found:', error.message);\n  } else if (error instanceof InvalidManagerConfigError) {\n    console.error('Invalid manager type:', error.message);\n  }\n}\n\ntry {\n  const model = getModel(Storehouse, 'nonexistent');\n} catch (error) {\n  if (error instanceof ModelNotFoundError) {\n    console.error('Model not found:', error.message);\n  }\n}\n```\n\n## Best Practices\n\n1. **Always connect** - Call `connect()` after registering the manager to establish the connection\n2. **Use health checks** - Monitor connection health in production environments\n3. **Handle disconnections** - Implement reconnection and retry logic for critical operations\n4. **Close connections** - Always call `close()` when shutting down your application\n5. **Use TypeScript** - Leverage type definitions for safer database operations\n\n## Resources\n\n- [Documentation](https://kisiwu.github.io/storehouse/mongodb/latest/)\n- [@storehouse/core](https://www.npmjs.com/package/@storehouse/core)\n- [MongoDB Node.js Driver](https://www.npmjs.com/package/mongodb)\n- [MongoDB Documentation](https://www.mongodb.com/docs/)\n\n## License\n\nMIT","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkisiwu%2Fstorehouse-mongodb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkisiwu%2Fstorehouse-mongodb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkisiwu%2Fstorehouse-mongodb/lists"}