UNPKG

mongodb-connection-lib

Version:

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

103 lines (92 loc) 2.54 kB
const DatabaseService = require("../services/DatabaseService"); const { ObjectId } = require("mongodb"); class BaseModel { constructor(data = {}) { Object.assign(this, data); if (!this.createdAt) this.createdAt = new Date(); this.updatedAt = new Date(); } static get collectionName() { throw new Error("Collection name must be defined in child class"); } async save() { try { if (this._id) { // Update existing document const { _id, ...updateData } = this; updateData.updatedAt = new Date(); await DatabaseService.updateOne( this.constructor.collectionName, { _id: new ObjectId(_id) }, { $set: updateData } ); } else { // Create new document const result = await DatabaseService.insertOne( this.constructor.collectionName, this ); this._id = result.insertedId; } return this; } catch (error) { throw error; } } static async findById(id) { try { const objectId = new ObjectId(id); return await DatabaseService.findOne(this.collectionName, { _id: objectId, }); } catch (error) { throw error; } } static async findOne(query = {}, options = {}) { try { return await DatabaseService.findOne(this.collectionName, query, options); } catch (error) { throw error; } } static async find(query = {}, options = {}) { try { return await DatabaseService.find(this.collectionName, query, options); } catch (error) { throw error; } } static async updateById(id, updateData) { try { const objectId = new ObjectId(id); updateData.updatedAt = new Date(); return await DatabaseService.updateOne( this.collectionName, { _id: objectId }, { $set: updateData } ); } catch (error) { throw error; } } static async deleteById(id) { try { const objectId = new ObjectId(id); return await DatabaseService.deleteOne(this.collectionName, { _id: objectId, }); } catch (error) { throw error; } } static async count(query = {}) { try { const collection = DatabaseService.getCollection(this.collectionName); return await collection.countDocuments(query); } catch (error) { throw error; } } } module.exports = BaseModel;