43 lines
1.3 KiB
JavaScript
43 lines
1.3 KiB
JavaScript
const mongodb = require('mongodb');
|
|
const assert = require('assert');
|
|
|
|
const mongoConfig = {
|
|
url: 'mongodb://localhost:27017',
|
|
username: 'express-user',
|
|
password: 'P@ssword1',
|
|
database: 'express-test'
|
|
}
|
|
|
|
class Mongo {
|
|
constructor() {
|
|
mongodb.MongoClient.connect(mongoConfig.url, (err, client) => {
|
|
assert.equal(null, err);
|
|
console.log('Connected successfuly to mongodb');
|
|
this.db = client.db(mongoConfig.database);
|
|
|
|
this.db.collection('test').find({}, (err, results) => {
|
|
results.forEach(console.log);
|
|
});
|
|
|
|
client.close();
|
|
})
|
|
}
|
|
|
|
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.`);
|
|
callback(result);
|
|
})
|
|
}
|
|
|
|
update(collectionName, entity, query, callback) {
|
|
this.db.collection(collectionName).update(query, entity, (error, result) => {
|
|
assert.equal(null, error, `Unable to update ${collectionName} entity: ${error}.`);
|
|
console.log(`Entity ${collectionName} updated.`);
|
|
callback(result);
|
|
})
|
|
}
|
|
}
|
|
|
|
module.exports = Mongo; |