UNPKG

mongodb-connection-lib

Version:

A comprehensive MongoDB connection library with CRUD operations, connection pooling, and model abstraction

205 lines (182 loc) 6.15 kB
const { MongoClient } = require("mongodb"); const databaseConfig = require("../config/database"); const Logger = require("../utils/logger"); class DatabaseService { constructor() { this.client = null; this.db = null; this.isConnected = false; } async connect() { try { Logger.info("Attempting to connect to MongoDB..."); this.client = new MongoClient( databaseConfig.getConnectionString(), databaseConfig.getOptions() ); await this.client.connect(); this.db = this.client.db(databaseConfig.getDatabaseName()); this.isConnected = true; Logger.info("Successfully connected to MongoDB"); // Test the connection await this.db.admin().ping(); Logger.info("MongoDB ping successful"); return this.db; } catch (error) { Logger.error("Failed to connect to MongoDB:", error); throw error; } } async disconnect() { try { if (this.client) { await this.client.close(); this.isConnected = false; Logger.info("Disconnected from MongoDB"); } } catch (error) { Logger.error("Error disconnecting from MongoDB:", error); throw error; } } getDatabase() { if (!this.isConnected || !this.db) { throw new Error("Database not connected. Call connect() first."); } return this.db; } getCollection(collectionName) { const db = this.getDatabase(); return db.collection(collectionName); } async healthCheck() { try { if (!this.isConnected) { return { status: "disconnected", message: "Not connected to database" }; } await this.db.admin().ping(); return { status: "healthy", message: "Database connection is healthy" }; } catch (error) { Logger.error("Health check failed:", error); return { status: "unhealthy", message: error.message }; } } // CRUD Operations async insertOne(collectionName, document) { try { const collection = this.getCollection(collectionName); const result = await collection.insertOne(document); Logger.debug( `Inserted document into ${collectionName}:`, result.insertedId ); return result; } catch (error) { Logger.error(`Error inserting document into ${collectionName}:`, error); throw error; } } async insertMany(collectionName, documents) { try { const collection = this.getCollection(collectionName); const result = await collection.insertMany(documents); Logger.debug( `Inserted ${result.insertedCount} documents into ${collectionName}` ); return result; } catch (error) { Logger.error(`Error inserting documents into ${collectionName}:`, error); throw error; } } async findOne(collectionName, query = {}, options = {}) { try { const collection = this.getCollection(collectionName); const result = await collection.findOne(query, options); Logger.debug(`Found document in ${collectionName}`); return result; } catch (error) { Logger.error(`Error finding document in ${collectionName}:`, error); throw error; } } async find(collectionName, query = {}, options = {}) { try { const collection = this.getCollection(collectionName); const cursor = collection.find(query, options); const results = await cursor.toArray(); Logger.debug(`Found ${results.length} documents in ${collectionName}`); return results; } catch (error) { Logger.error(`Error finding documents in ${collectionName}:`, error); throw error; } } async updateOne(collectionName, query, update, options = {}) { try { const collection = this.getCollection(collectionName); const result = await collection.updateOne(query, update, options); Logger.debug( `Updated document in ${collectionName}:`, result.modifiedCount ); return result; } catch (error) { Logger.error(`Error updating document in ${collectionName}:`, error); throw error; } } async updateMany(collectionName, query, update, options = {}) { try { const collection = this.getCollection(collectionName); const result = await collection.updateMany(query, update, options); Logger.debug( `Updated ${result.modifiedCount} documents in ${collectionName}` ); return result; } catch (error) { Logger.error(`Error updating documents in ${collectionName}:`, error); throw error; } } async deleteOne(collectionName, query) { try { const collection = this.getCollection(collectionName); const result = await collection.deleteOne(query); Logger.debug( `Deleted document from ${collectionName}:`, result.deletedCount ); return result; } catch (error) { Logger.error(`Error deleting document from ${collectionName}:`, error); throw error; } } async deleteMany(collectionName, query) { try { const collection = this.getCollection(collectionName); const result = await collection.deleteMany(query); Logger.debug( `Deleted ${result.deletedCount} documents from ${collectionName}` ); return result; } catch (error) { Logger.error(`Error deleting documents from ${collectionName}:`, error); throw error; } } async aggregate(collectionName, pipeline, options = {}) { try { const collection = this.getCollection(collectionName); const cursor = collection.aggregate(pipeline, options); const results = await cursor.toArray(); Logger.debug(`Aggregation completed for ${collectionName}`); return results; } catch (error) { Logger.error(`Error in aggregation for ${collectionName}:`, error); throw error; } } } module.exports = new DatabaseService();