const mongodb = require('mongodb'); const configuration = require('../configuration'); const mongoConfig = configuration.database; class MongoClient { constructor() { mongodb.MongoClient.connect(mongoConfig.url, (error, client) => { console.log(error); if (error !== null) { throw new Error(`Unable de connect to Mongo database: ${error}`); } console.log('Connected successfuly to mongodb'); this.db = client.db(mongoConfig.database); }); } find(collectionName, query, callback) { this.db.collection(collectionName).find(query).toArray() .then(results => { console.log(`Entities ${collectionName} founded.`); callback(results); }) .catch(error => { throw new Error(`Unable to find entities in collection ${collectionName}: ${error}`); }); } insert(collectionName, entity, callback) { this.db.collection(collectionName).insertOne(entity, (error, result) => { if (error !== null) { throw new Error(`Unable to insert ${collectionName} entity: ${error}`); } console.log(`Entity ${collectionName} inserted.`); // Return only the inserted document. callback(result.ops[0]); }); } update(collectionName, entity, callback) { this.db.collection(collectionName).updateOne({_id: mongodb.ObjectId(entity._id)}, {$set: entity}, {upsert: true}, (error) => { if (error !== null) { throw new Error(`Unable to update ${collectionName} entity: ${error}`); } console.log(`Entity ${collectionName} updated.`); callback(); }); } delete(collectionName, entityId, callback) { this.db.collection(collectionName).deleteOne({_id: mongodb.ObjectId(entityId)}, (error) => { if (error !== null) { throw new Error(`Unable to delete ${collectionName} entity with id ${entityId}: ${error}`); } console.log(`Entity ${collectionName} with id ${entityId} deleted.`); callback(); }); } } // Define a singleton of class "MongoClient". const mongoClient = new MongoClient(); module.exports = mongoClient;