-
Notifications
You must be signed in to change notification settings - Fork 0
/
databaseControl.js
68 lines (65 loc) · 2.01 KB
/
databaseControl.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
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
const ObjectId = mongodb.ObjectId
const mongodbUrl = 'mongodb://127.0.0.1:27017'
class MongoControl {
constructor(dbName, collectionName) {
this.dbName = dbName
this.collectionName = collectionName
}
_init(callback) {
MongoClient.connect(mongodbUrl, { useNewUrlParser: true }, (error, client) => {
if (error) {
callback(error)
return
}
var db = client.db(this.dbName)
callback(null, db.collection(this.collectionName), client)
})
}
find(findQuery, callback) {
this._init((err, collection, client) => {
collection.find(findQuery).toArray(function (err, res) {
callback(err, res)
client.close()
})
})
}
insert(docs, callback) {
this._init((err, collection, client) => {
collection.insert(docs, (err, res) => {
callback(err, res)
client.close()
})
})
}
update(findQuery, newDate, callback) {
this._init((err, collection, client) => {
collection.update(findQuery, { $set: newDate }, (err, res) => {
callback(err, res)
client.close()
})
})
}
remove(findQuery, callback) {
this._init((err, collection, client) => {
collection.remove(findQuery, (err, res) => {
callback(err, res.result)
client.close()
})
})
}
removeById(_id, callback) {
var findQuery = { _id: ObjectId(_id) }
this.remove(findQuery, callback)
}
updateById(_id, newDocs, callback) {
var findQuery = { _id: ObjectId(_id) }
this.update(findQuery, newDocs, callback)
}
findById(_id, callback) {
var findQuery = { _id: ObjectId(_id) }
this.find(findQuery, callback)
}
}
exports.MongoControl = MongoControl