-
Notifications
You must be signed in to change notification settings - Fork 29
/
db.js
70 lines (68 loc) · 1.79 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
const { MongoClient, ObjectID } = require('mongodb');
const assert = require('assert');
const config = require('./config');
const url = `mongodb://${config.mongoHost}:27017`;
const dbname = 'bitcoin-faucet';
module.exports = {
id(id) {
return new ObjectID(id);
},
connect(cb) {
assert(!this.connected);
MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
assert.equal(null, err);
this.connected = true;
this.db = client.db(dbname);
cb(err);
});
},
disconnect() {
assert(this.connected);
this.db.close();
this.connected = false;
this.db = null;
},
insert(coll, obj, cb) {
return this.db.collection(coll).insertOne(obj, cb);
},
find(coll, query, sort, cb) {
if (!cb) {
cb = sort;
sort = null;
}
const cursor = this.db.collection(coll).find(query);
if (sort) cursor.sort(sort);
cursor.toArray(cb);
},
update(coll, query, set, cb = null) {
this.db.collection(coll).update(
query,
{
$set: set,
$currentDate: { "lastModified": true },
},
cb
);
},
upsert(coll, query, set, cb = null) {
this.db.collection(coll).update(
query,
{
$set: set,
$currentDate: { "lastModified": true },
},
{
upsert: true,
},
cb
);
},
remove(coll, query, cb = null) {
this.db.collection(coll).deleteOne(query, (err, results) => {
if (cb)
cb(err, results);
else
assert.equal(null, err);
});
},
};