-
Notifications
You must be signed in to change notification settings - Fork 0
/
collectionDriver.js
49 lines (47 loc) · 1.63 KB
/
collectionDriver.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
var ObjectID = require('mongodb').ObjectID;
CollectionDriver = function(db) {
this.db = db;
};
CollectionDriver.prototype.getCollection = function(collectionName, callback) {
this.db.collection(collectionName, function(error, the_collection) {
if( error ) callback(error);
else callback(null, the_collection);
});
};
CollectionDriver.prototype.findAll = function(collectionName, callback) {
this.getCollection(collectionName, function(error, the_collection) {
if( error ) callback(error);
else {
the_collection.find().toArray(function(error, results) {
if( error ) callback(error);
else callback(null, results);
});
}
});
};
CollectionDriver.prototype.get = function(collectionName, id, callback) {
this.getCollection(collectionName, function(error, the_collection) {
if (error) callback(error);
else {
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
if (!checkForHexRegExp.test(id)) callback({error: "invalid id"});
else the_collection.findOne({'_id':ObjectID(id)}, function(error,doc) {
if (error) callback(error);
else callback(null, doc);
});
}
});
};
//save new object
CollectionDriver.prototype.save = function(collectionName, obj, callback) {
this.getCollection(collectionName, function(error, the_collection) { //A
if( error ) callback(error)
else {
obj.created_at = new Date(); //B
the_collection.insert(obj, function() { //C
callback(null, obj);
});
}
});
};
exports.CollectionDriver = CollectionDriver;