-
Notifications
You must be signed in to change notification settings - Fork 1
/
import_questions.js
executable file
·75 lines (64 loc) · 2.3 KB
/
import_questions.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
#!/usr/bin/env node
/**
* import_questions.js
* Imports questions into the database.
*/
var program = require('commander');
program
.option('-f, --question-file <file name>', 'JSON file with questions to import')
.option('-d, --database-name <name>', 'Database to import to')
.option('-c, --collection-name <name>', 'Collection to import to')
.parse(process.argv);
var mongodb = require('mongodb'),
server = new mongodb.Server('127.0.0.1', '27017', {}),
connection = new mongodb.Db(program.databaseName, server, { safe: false }),
ObjectID = require('mongodb').ObjectID,
querystring = require('querystring'),
util = require('util'),
fs = require('fs'),
step = require('step');
connection.open(function (err, conn) {
if (err) {
process.stdout.write('Could not open connection.');
process.exit(-1);
}
conn.collection(program.collectionName, function (err, questions) {
if (err) {
process.stdout.write('Could not open collection.');
process.exit(-1);
}
fs.readFile(program.questionFile, function (err, data) {
if (err) {
process.stdout.write('Could not open file.');
process.exit(-1);
}
if (!data.length)
process.exit(-1);
var docs = JSON.parse(data);
if (docs.length < 1)
process.exit(-1);
step(
function () {
var callbackFactory = this;
docs.forEach(function (doc) {
if (typeof doc._id !== 'undefined') {
doc._id = ObjectID(doc._id);
}
if (typeof doc.id !== 'undefined') {
doc._id = ObjectID(doc.id);
delete doc.id;
}
questions.insert(doc, { safe: true }, callbackFactory.parallel());
});
},
function (err) {
if (err) {
console.error(err);
process.exit(-1);
}
process.exit(0);
}
);
});
});
});