-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongoWidgetScript.js
92 lines (90 loc) · 3 KB
/
mongoWidgetScript.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
const mongoClient = require('mongodb').MongoClient;
const mongoURL = "mongodb://localhost:27017";
const dbName = 'smartmirror'
const collectionName = 'widgets'
const async = require('async');
const myDocs = [
{"name": "ClockWidget"},
{"name": "NewsFeed"},
{"name": "QuotesWidget"},
{"name": "ToDoWidget"},
{"name": "WeatherWidget"},
{"name": "CalendarWidget"},
{"name": "IndoorWidget"},
{"name": "OutdoorWidget"}
];
//mongo DB insertion (using async series)
async.waterfall([
//function array...
function (callback) {
//database connect
console.log("DB Connect");
mongoClient.connect(mongoURL, { useNewUrlParser: true }, function (err, mgo) {
if (err) callback(err, mgo);
callback(null, mgo);
});
},
function (mgo, callback) {
//list collections
console.log("List Collections");
var db = mgo.db(dbName);
var names = [];
db.listCollections().toArray(function (err, collinfo) {
if (err) callback(err, mgo);
for (coll in collinfo) {
names.push(collinfo[coll].name);
console.log(collinfo[coll].name);
}
callback(null, mgo, names);
});
},
function (mgo, names, callback) {
//drop collection (if pre-existing)
console.log("Collection '" + collectionName + "'");
var db = mgo.db(dbName);
if (names.includes(collectionName)) {
db.dropCollection(collectionName, function (err, res) {
if (err) callback(err, mgo);
console.log("dropped");
callback(null, mgo);
});
} else {
console.log("not found");
callback(null, mgo);
}
},
function (mgo, callback) {
//create collection
console.log("Create Collection 'deviceApps'");
var db = mgo.db(dbName);
db.createCollection(collectionName, function (err, coll) {
if (err) callback(err, mgo);
callback(null, mgo, coll);
});
},
function (mgo, coll, callback) {
//insert documents
console.log("Insert Documents");
coll.insertMany(myDocs, function (err, res) {
if (err) callback(err, mgo);
callback(null, mgo);
});
},
function (mgo, callback) {
//close connection
console.log("DB close");
try {
mgo.close();
callback(null, null);
} catch (err) {
callback(err, mgo);
}
}],
//post array function
function (err, mgo) {
//db close, error logging
if (mgo) mgo.close();
if (err) console.log(err);
else console.log("Done without Errors");
}
);