-
Notifications
You must be signed in to change notification settings - Fork 0
/
install_data.js
79 lines (69 loc) · 2.09 KB
/
install_data.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
import * as mongodb from 'mongodb';
import fs from 'fs';
import 'dotenv/config';
const client = new mongodb.MongoClient(process.env.MONGODB_URI);
function connectToMongo(callback){
client.connect((err, client)=>{
if(err || !client)
return callback(err);
return callback(err);
});
}
function getDB(dbName){
return client.db(dbName);
}
var counter = 0;
const list = ['users', 'posts', 'comments', 'reports', 'likes'];
/**
*
* @param {mongodb.Db} db
* @param {String} name
*/
async function addData(db, name){
console.log('Adding ' + name + ' data to db...');
//CREATE COLLECTION
//@ts-ignore
db.createCollection(name).then(collection=>{
if(collection != null)
console.log('Collection ' + name + ' created!');
}).catch(error=>{
console.error('Error occured while adding ' + name + ':');
console.error(error);
return;
});
//READ DATA
let raw = fs.readFileSync('./.installation/' + name + '.json');
let json = JSON.parse(String(raw));
//delete json._id;
for(var i = 0; i < json.length; i++){
var oid = json[i]['_id']['$oid'];
json[i]['_id'] = new mongodb.ObjectId(String(oid));
}
//ADD DATA
var collection = db.collection(name);
if(collection){
await collection.insertMany(json).then((result)=>{
counter++;
console.log('Collection ' + name + ' acknowledged: ' + result.acknowledged + ' @ ' + result.insertedCount + ' documents inserted');
if(counter == list.length){
console.log('Full data installation completed!')
client.close();
process.exit();
}
});
}else{
console.log('Collection ' + name + ' is null');
}
}
connectToMongo((err, callback)=>{
if(err){
console.error(err);
console.log('Exiting...');
process.exit();
}
const DBNAME = process.env.DB_NAME;
const db = getDB(DBNAME);
console.log('Adding contents to database: ' + DBNAME);
for(var l of list)
addData(db, l);
});