/
document.js
91 lines (71 loc) · 2.23 KB
/
document.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
var config = require('../config');
var bson = require('../bson');
exports.viewDocument = function(req, res, next) {
var ctx = {
title: 'Viewing Document: ' + req.document._id,
editorTheme: config.options.editorTheme,
docString: bson.toString(req.document)
};
res.render('document', ctx);
};
exports.addDocument = function(req, res, next) {
var doc = req.body.document;
if (doc == undefined || doc.length == 0) {
req.session.error = "You forgot to enter a document!";
return res.redirect('back');
}
var docBSON;
try {
docBSON = bson.toBSON(doc);
} catch (err) {
req.session.error = "That document is not valid!";
console.error(err);
return res.redirect('back');
}
req.collection.insert(docBSON, {safe: true}, function(err, result) {
if (err) {
req.session.error = "Something went wrong: " + err;
console.error(err);
return res.redirect('back');
}
req.session.success = "Document added!";
res.redirect('/db/' + req.dbName + '/' + req.collectionName);
});
};
exports.updateDocument = function(req, res, next) {
var doc = req.body.document;
if (doc == undefined || doc.length == 0) {
req.session.error = "You forgot to enter a document!";
return res.redirect('back');
}
var docBSON;
try {
docBSON = bson.toBSON(doc);
} catch (err) {
req.session.error = "That document is not valid!";
console.error(err);
return res.redirect('back');
}
docBSON._id = req.document._id;
req.collection.update(req.document, docBSON, {safe: true}, function(err, result) {
if (err) {
//document was not saved
req.session.error = "Something went wrong: " + err;
console.error(err);
return res.redirect('back');
}
req.session.success = "Document updated!";
res.redirect('/db/' + req.dbName + '/' + req.collectionName);
});
};
exports.deleteDocument = function(req, res, next) {
req.collection.remove(req.document, {safe: true}, function(err, result) {
if (err) {
req.session.error = "Something went wrong! " + err;
console.error(err);
return res.redirect('back');
}
req.session.success = "Document deleted!";
res.redirect('/db/' + req.dbName + '/' + req.collectionName);
});
};