-
Notifications
You must be signed in to change notification settings - Fork 521
/
initDB.js
61 lines (46 loc) · 1.65 KB
/
initDB.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
/*
This script will initialize a local Mongo database
on your machine so you can do development work.
IMPORTANT: You should make sure the
local_database_name
variable matches its value in app.js Otherwise, you'll have
initialized the wrong database.
*/
var mongoose = require('mongoose');
var models = require('./models');
// Connect to the Mongo database, whether locally or on Heroku
// MAKE SURE TO CHANGE THE NAME FROM 'lab7' TO ... IN OTHER PROJECTS
var local_database_name = 'lab7';
var local_database_uri = 'mongodb://localhost/' + local_database_name
var database_uri = process.env.MONGOLAB_URI || local_database_uri
mongoose.connect(database_uri);
// Do the initialization here
// Step 1: load the JSON data
var projects_json = require('./projects.json');
// Step 2: Remove all existing documents
models.Project
.find()
.remove()
.exec(onceClear); // callback to continue at
// Step 3: load the data from the JSON file
function onceClear(err) {
if(err) console.log(err);
// loop over the projects, construct and save an object from each one
// Note that we don't care what order these saves are happening in...
var to_save_count = projects_json.length;
for(var i=0; i<projects_json.length; i++) {
var json = projects_json[i];
var proj = new models.Project(json);
proj.save(function(err, proj) {
if(err) console.log(err);
to_save_count--;
console.log(to_save_count + ' left to save');
if(to_save_count <= 0) {
console.log('DONE');
// The script won't terminate until the
// connection to the database is closed
mongoose.connection.close()
}
});
}
}