UNPKG

mongoose-database-schema

Version:

MongoDB database documentation generator with table schemas and relationships

56 lines (47 loc) 1.42 kB
const { MongoClient } = require('mongodb'); class DatabaseConnection { constructor(connectionString, dbName) { this.connectionString = connectionString; this.dbName = dbName; this.client = null; this.db = null; } async connect() { try { this.client = new MongoClient(this.connectionString); await this.client.connect(); this.db = this.client.db(this.dbName); console.log(`Connected to MongoDB database: ${this.dbName}`); return this.db; } catch (error) { console.error('Database connection failed:', error); throw error; } } async disconnect() { if (this.client) { await this.client.close(); console.log('Database connection closed'); } } async getCollections() { if (!this.db) { throw new Error('Database not connected'); } const collections = await this.db.listCollections().toArray(); return collections.map(col => col.name); } async getCollectionStats(collectionName) { if (!this.db) { throw new Error('Database not connected'); } const collectionStats = await this.db.collection(collectionName).stats(); return { totalDocuments: collectionStats.count, avgDocumentSize: collectionStats.avgObjSize, totalSize: collectionStats.size, indexCount: collectionStats.nindexes }; } } module.exports = DatabaseConnection;