UNPKG

mongodb-connection-lib

Version:

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

81 lines (71 loc) 1.83 kB
const DatabaseService = require("../services/DatabaseService"); const { ObjectId } = require("mongodb"); class User { constructor(data) { this.name = data.name; this.email = data.email; this.age = data.age; this.createdAt = new Date(); this.updatedAt = new Date(); } static get collectionName() { return "users"; } async save() { try { const result = await DatabaseService.insertOne(User.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(User.collectionName, { _id: objectId, }); } catch (error) { throw error; } } static async findByEmail(email) { try { return await DatabaseService.findOne(User.collectionName, { email }); } catch (error) { throw error; } } static async findAll(query = {}, options = {}) { try { return await DatabaseService.find(User.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( User.collectionName, { _id: objectId }, { $set: updateData } ); } catch (error) { throw error; } } static async deleteById(id) { try { const objectId = new ObjectId(id); return await DatabaseService.deleteOne(User.collectionName, { _id: objectId, }); } catch (error) { throw error; } } } module.exports = User;