Add mongo code

This commit is contained in:
Arti Zirk 2017-05-11 11:22:47 +03:00
parent 2ef46bbd8e
commit 5af7522902
2 changed files with 72 additions and 13 deletions

14
dao.js
View File

@ -2,7 +2,7 @@
const mongodb = require('mongodb');
const ObjectID = require('mongodb').ObjectID;
const COLLECTION = 'test-collection';
const COLLECTION = 'contacts';
class Dao {
@ -15,6 +15,18 @@ class Dao {
return this.db.collection(COLLECTION).find().toArray();
}
findById(id) {
id = new ObjectID(id);
return this.db.collection(COLLECTION).findOne({_id:id});
}
update(id, data) {
id = new ObjectID(id);
data._id = id
return this.db.collection(COLLECTION)
.updateOne({_id:id}, data);
}
close() {
if (this.db) {
this.db.close();

View File

@ -4,20 +4,67 @@ const mongodb = require('mongodb');
const Dao = require('./dao.js');
const ObjectID = mongodb.ObjectID;
var url = 'mongodb://...';
var url = 'mongodb://i399:salakala@ds137191.mlab.com:37191/i399';
var data = { name: 'Jill' };
var data = { name: 'John' };
//findById("591418e3930698683597d4f8").then(data => console.log(data))
var dao = new Dao();
dao.connect(url)
.then(() => {
return dao.findById('591418e3930698683597d4f8')
}).then(data => {
dao.close();
console.log(data);
}).catch(error => {
dao.close();
console.log('Error: ' + error)
});
function inset(data) {
var database;
mongodb.MongoClient.connect(url).then(db => {
database = db;
return db.collection('test-collection').insertOne(data);
return db.collection('contacts').insertOne(data);
}).then(() => {
closeDb(database)
}).catch(error => {
closeDb(database);
throw error;
});
}
function findAll() {
var database;
return mongodb.MongoClient.connect(url).then(db => {
database = db;
return db.collection('contacts').find().toArray();
}).then(data => {
closeDb(database)
return data;
}).catch(error => {
closeDb(database);
throw error;
});
}
function findById(id) {
var database;
return mongodb.MongoClient.connect(url).then(db => {
database = db;
id = new ObjectID(id)
return db.collection('contacts').findOne({ _id: id});
}).then(data => {
closeDb(database)
return data;
}).catch(error => {
closeDb(database);
throw error;
});
}
function closeDb(database) {
if (database) {