This repository has been archived by the owner on Dec 31, 2018. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
70 lines (61 loc) · 1.7 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
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
//Create a database named "mydb":
const url = "mongodb://localhost:27017";
const database = "flagbrew"
function connect(callback) {
MongoClient.connect(url, {useNewUrlParser: true}, callback)
}
function insert_data(collectionName, data, name) {
// connect to the database
connect(function (err, client) {
let db = client.db(database)
assert.equal(null, err);
console.log("inserting data please wait!")
let collection = db.collection(collectionName)
try {
console.log(name)
collection.updateOne({ "name": name, }, {$set: data}, {upsert: true})
} catch(e) {
console.log(e)
}
// close the connection after we're done
console.log("data inserted, closing connection!")
client.close()
})
}
function fetch_all(collectionName, callback) {
connect(function (err, client) {
let db = client.db(database)
assert.equal(null, err);
let collection = db.collection(collectionName)
collection.find({}).toArray(function (err, result) {
assert.equal(null, err);
callback(result)
})
client.close()
})
}
function fetch_one(collectionName, name, callback) {
connect(function (err, client) {
let db = client.db(database)
assert.equal(null, err);
let collection = db.collection(collectionName)
collection.findOne({name: name}, function (err, result) {
assert.equal(null, err);
callback(result)
})
client.close()
})
}
module.exports = {
insert: function (collection, data, name) {
insert_data(collection, data, name)
},
get_all: function (collection, callback) {
fetch_all(collection, callback)
},
get_one: function (collection, name, callback) {
fetch_one(collection, name, callback)
}
};