-
Notifications
You must be signed in to change notification settings - Fork 0
/
employeeprovider.js
68 lines (58 loc) · 2.17 KB
/
employeeprovider.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
EmployeeProvider = function(host, port) {
this.db= new Db('node-mongo-employee', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
EmployeeProvider.prototype.getCollection= function(callback) {
this.db.collection('employees', function(error, employee_collection) {
if( error ) callback(error);
else callback(null, employee_collection);
});
};
//find all employees
EmployeeProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, employee_collection) {
if( error ) callback(error)
else {
employee_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
//save new employee
EmployeeProvider.prototype.save = function(employees, callback) {
this.getCollection(function(error, employee_collection) {
if( error ) callback(error)
else {
if( typeof(employees.length)=="undefined")
employees = [employees];
for( var i =0;i< employees.length;i++ ) {
employee = employees[i];
employee.created_at = new Date();
}
employee_collection.insert(employees, function() {
callback(null, employees);
});
}
});
};
EmployeeProvider.prototype.delete = function(employeeId, callback) {
this.getCollection(function(error, employee_collection) {
if(error) callback(error);
else {
employee_collection.remove(
{_id: employee_collection.db.bson_serializer.ObjectID.createFromHexString(employeeId)},
function(error, employee){
if(error) callback(error);
else callback(null, employee)
});
}
});
};
exports.EmployeeProvider = EmployeeProvider;