52 lines
1.9 KiB
JavaScript
52 lines
1.9 KiB
JavaScript
const mongodb = require('mongodb');
|
|
const assert = require('assert');
|
|
|
|
const configuration = require('../configuration');
|
|
const mongoConfig = configuration.database;
|
|
|
|
class MongoClient {
|
|
constructor() {
|
|
mongodb.MongoClient.connect(mongoConfig.url, (error, client) => {
|
|
assert.equal(null, error, `Unable to connect to mongodb: ${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 => console.error(error));
|
|
}
|
|
|
|
insert(collectionName, entity, callback) {
|
|
this.db.collection(collectionName).insert(entity, (error, result) => {
|
|
assert.equal(null, 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).save(entity, (error) => {
|
|
assert.equal(null, 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) => {
|
|
assert.equal(null, error, `Unable to delete ${collectionName} entity with id ${entityId}: ${error}.`);
|
|
console.log(`Entity ${collectionName} with id ${entityId} deleted.`);
|
|
callback();
|
|
});
|
|
}
|
|
}
|
|
|
|
const mongoClient = new MongoClient();
|
|
module.exports = mongoClient; |