This repository has been archived by the owner on Jan 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
98 lines (88 loc) · 2.5 KB
/
db.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var MongoClient=require("mongodb").MongoClient;
var log=require("./log")("db");
var self=exports=module.exports={};
//todo: replace config here and authenticate
self.url="mongodb://localhost:27017";
if(process.env.OPENSHIFT){
var uri=process.env.DATABASE_URI;
if(uri) self.url=uri;
}
self.dbName = 'farewell';
self.connect=function(callback){
MongoClient.connect(self.url, function(err, client) {
if(err){
log.error(err.stack);
if(callback) callback(err);
}
log.info("connected to mongodb");
self.db=client.db(self.dbName);
self.client=client;
if(callback) callback(null);
});
}
//zing(Error err) logs an error if present
var zing=function(err){
if(err) log.error(err.stack);
}
var getCollection=self.getCollection=function(name){
if(typeof name==typeof {}) return name;
if(!name)return name;
return self.db.collection(name);
}
var insertMany=self.insertMany=function(collection,documents,callback){
collection=getCollection(collection);
collection.insertMany(documents,function(err,result){
zing(err);
if(callback) callback(err,result);
});
};
var insertOne=self.insertOne=function(collection,document,callback){
collection=getCollection(collection);
collection.insertOne(document,function(err,result){
zing(err);
if(callback) callback(err,result);
});
};
var insert=self.insert=function(collection,doc,cb){
if(!doc){
callback(new TypeError("document missing!"));
return;
}
if(doc.length){
return insertMany(collection,doc,cb);
}else{
return insertOne(collection,doc,cb);
}
};
var find=self.find=function(collection,filter,callback){
collection=getCollection(collection);
if(typeof filter==typeof zing){//2nd param is a function
callback=filter;
filter={};
}
collection.find(filter).toArray(function(err, docs) {
zing(err);
callback(err,docs);
});
}
var updateMany=self.updateMany=function(collection,filter,update,callback){
collection=getCollection(collection);
collection.updateMany(filter,update,function(err,result){
zing(err);
if(callback) callback(err,result);
});
};
var updateOne=self.updateOne=function(collection,filter,update,callback){
collection=getCollection(collection);
collection.updateOne(filter,update,function(err,result){
zing(err);
if(callback) callback(err,result);
});
};
var deleteOne=self.deleteOne=function(collection,query,callback){
collection=getCollection(collection);
return collection.deleteOne(query,function(err,result){
zing(err);
if(callback)callback(err,result);
});
};