-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoc.js
1232 lines (1169 loc) · 41.2 KB
/
doc.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const crypto = require('crypto');
const fs = require('fs');
const ObjectID = require('mongodb').ObjectID;
const docModel = require('../models/doc');
const textUtil = require('../public/js/util.js');
const conf = require('../config/conf');
const package = require('../package.json');
const csurf = require('csurf');
var csrfProtection = csurf();
var querymen = require('querymen');
var qs = require('querystring');
var jsonpatch = require('json-patch-extended');
const path = require('path');
const os = require('os');
const Busboy = require('busboy');
const {
check,
validationResult
} = require('express-validator/check');
const {
matchedData,
sanitize
} = require('express-validator/filter');
const validator = require('validator');
module.exports = function (name, opts) {
//todo make it configurable
var idpath = opts.facet.ID.path;
if(undefined == opts.facet.ID.link) {
opts.facet.ID.href = '/' +name+ '/';
}
var jsonidpath = idpath.substr(5);
var idpattern = opts.facet.ID.regex;
//idpath, idpattern, querySchema, facetSchema, qProject, tFacet) {
var queryDef = {
q: {
normalize: false,
type: [String],
default: null,
escape: true,
paths: ["$text"],
operator: "$search",
/*formatter: function (txt, v, p) {
return v.replace(/([A-Z]+-[0-9A-Za-z-]+)/g, "\"$1\"");
}*/
},
sort: {
default: 'ID'
},
limit: {
default: 100,
max: 22000
}
};
var project = {};
var columns = [];
var tabFacet = {};
var bulkInput = {};
var toIndex = {};
var defaultSort = {};
var lookups = [];
var chartFacet = {
count: [{
$count: "total"
}]
};
var chartCount = 0;
for (key in opts.facet) {
var options = opts.facet[key];
queryDef[key] = {
type: [String],
paths: [options.path]
}
if (options.type) {
queryDef[key].type = options.type;
}
if (options.hasOwnProperty('default')) {
queryDef[key].default = options.default;
}
if (options.queryOperator) {
queryDef[key].operator = options.queryOperator;
}
if (!options.hideColumn) {
if (Array.isArray(options.path)) {
project[key] = { "$setUnion": [options.path.map(x => {return '$' + x})]
}
} else if (typeof options.path === 'string') {
project[key] = '$' + options.path;
} else if(Object.keys(options.path).length != 0) {
project[key] = options.path;
}
columns.push(key);
}
if(options.sortDefault) {
queryDef.sort.default = options.sortDefault;
}
//toIndex[options.path] = options.sort ? options.sort : 1;
if (options.tabs) {
toIndex[options.path] = options.sort ? options.sort : 1;
if (Array.isArray(options.pipeline)) {
tabFacet[key] = options.pipeline;
} else {
tabFacet[key] = [{
$sortByCount: '$' + options.path
}];
}
if (options.sort) {
tabFacet[key].push({
$sort: {
_id: options.sort
}
})
}
}
if (options.chart) {
chartCount++;
toIndex[options.path] = options.sort ? options.sort : 1;
if (Array.isArray(options.pipeline)) {
chartFacet[key] = options.pipeline;
} else {
chartFacet[key] = [{
$sortByCount: '$' + options.path
}];
}
if (options.sort) {
chartFacet[key].push({
$sort: {
_id: options.sort
}
})
}
}
if(options.bulk) {
if(options.enum) {
bulkInput[key] = {
type: 'select',
enum: options.enum
}
} else {
bulkInput[key] = {
type: 'input'
}
}
}
if(options.lookup) {
//console.log('OL:'+JSON.stringify(options.lookup));
lookups = lookups.concat(options.lookup);
}
}
function phraseSplit(searchString) {
var s1 = searchString.match(/\\?.|^$/g).reduce((p, c) => {
if(c === '"'){
p.quote ^= 1;
}else if(!p.quote && c === ' '){
p.a.push('');
}else{
p.a[p.a.length-1] += c.replace(/\\(.)/,"$1");
}
return p;
}, {a: ['']}).a;
return(s1);
}
var qSchema = new querymen.Schema(queryDef);
qSchema.formatter('escape', function (escape, value, param) {
var r = [];
if (escape) {
if(typeof value == 'string') {
r = phraseSplit(value);
} else if (Array.isArray(value)) {
for(v in value) {
r.push(v.phraseSplit(value));
}
}
}
var terms = "";
for(var term of r) {
terms = terms + ' "' + term + '" ';
}
return terms;
});
/* qSchema.formatter('nullify', function(escape, value, param){
console.log("NULLIFY CALLED!");
if (value === "null") {
return {$exists:false};
}
});
if(opts.facet.severity) {
qSchema.param('severity').option('nullify', true);
}*/
qSchema.param('q').option('escape', true);
var module = {};
var Document = module.Document = docModel(name);
var History = module.History = docModel(name + '_history');
//console.log(toIndex);
for(var x in toIndex) {
var o = {};
o[x] = toIndex[x];
delete o.createIndex;
//console.log(name + ' createIndex('+JSON.stringify(o)+')');
Document.collection.createIndex(o, {background: true});
}
module.createDoc = function (req, res) {
let errors = validationResult(req).array();
if (errors.length > 0) {
var msg = 'Error: ';
for (var e of errors) {
msg += e.param + ': ' + e.msg + ' ';
}
res.json({
type: 'err',
msg: msg
});
return;
}
let entry = new Document({
"body": req.body,
"author": req.user.username
});
entry.save(function (err, doc) {
if (err) {
res.json({
type: 'err',
msg: 'Error ' + err
});
return;
} else {
module.addHistory(null, doc);
res.json({
type: 'go',
to: deep_value(doc, idpath)
});
return;
}
});
return;
};
module.addHistory = function (oldDoc, newDoc) {
if (oldDoc === null) {
oldDoc = {
__v: -1,
_id: newDoc._id,
author: newDoc.author,
updatedAt: newDoc.updatedAt,
body: {}
}
}
var auditTrail = {
parent_id: oldDoc._id,
updatedAt: newDoc.updatedAt,
author: newDoc.author,
__v: oldDoc.__v + 1,
body: {
old_version: oldDoc.__v,
old_author: oldDoc.author,
old_date: oldDoc.updatedAt,
patch: jsonpatch.compare(oldDoc.body, newDoc.body),
},
};
//console.log(JSON.stringify(auditTrail));
//todo: eliminate mongoose and call InsertOne directly
if(auditTrail.body.patch.length > 0) {
History.bulkWrite([{
insertOne: {
document: auditTrail
}
}], function (err, d) {
if (err) {
console.log('Error: saving history ' + err);
} else {
}
});
return auditTrail;
} else {
return null;
}
}
module.upsertDoc = function (req, res) {
let errors = validationResult(req).array();
if (errors.length > 0) {
var msg = 'Error: ';
for (var e of errors) {
msg += e.param + ': ' + e.msg + ' ';
}
res.json({
type: 'err',
msg: msg
});
return;
}
//let doc = req.body;
let inputID = deep_value(req, idpath);
let entry = {
"body": req.body,
"author": req.user.username
};
let queryNewID = {};
let queryOldID = {};
queryNewID[idpath] = inputID;
queryOldID[idpath] = req.params.id;
var renaming = (req.params.id != inputID);
//console.log('req.params.id = ' + req.params.id + ' == ' + inputID)
Document.findOne(queryNewID).then((existingDoc) => {
if (existingDoc) {
// check Document ID is being renamed.
if (renaming) {
res.json({
type: 'err',
msg: 'Not saved. Document ' + inputID + ' exists. Save with a different ID or update the existing one.'
});
return;
}
}
var d = new Date();
newDoc = {
body: req.body,
author: req.user.username,
updatedAt: d
};
Document.findAndModify(
queryOldID, [], {
"$set": newDoc,
"$inc": {
__v: 1
},
"$setOnInsert": {
createdAt: d
}
}, {
"upsert": true
},
function (err, doc) {
if (doc && doc.value) {
module.addHistory(doc.value, newDoc);
} else {
module.addHistory(null, newDoc);
}
if (err) {
res.json({
type: 'err',
msg: 'Error! Document not Updated, ' + err
});
} else {
if (renaming) {
res.json({
type: 'go',
to: inputID
});
} else {
res.json({
type: 'saved'
});
}
}
return;
});
});
return;
};
var router;
if (opts.router) {
router = opts.router;
} else {
router = express.Router();
}
router.get('*', function (req, res, next) {
res.locals.schemaName = name;
res.locals.page = req.baseUrl + req.path;
next();
});
/* if (opts.style) {
//console.log('PATH: ' + path.join(__dirname, '/../', opts.schema));
router.use('/style.css', express.static(path.join(__dirname, '/../', opts.style)));
}*/
// ToDo eliminate, as it can be embedded
if (opts.schema) {
//console.log('PATH: ' + path.join(__dirname, '/../', opts.schema));
//router.use('/schema.js', express.static(path.join(__dirname, '/../', opts.schema)));
router.use('/schema.js', function(req, res){
res.send('docSchema = ' + JSON.stringify(opts.schema));
});
}
router.get('/render.js', function (req, res) {
res.compile(opts.render, {cache: true});
});
if (!opts.conf.readonly) {
router.get('/new', csrfProtection, function (req, res) {
res.render(opts.edit, {
title: 'New',
doc: null,
opts: opts,
idpath: jsonidpath,
textUtil: textUtil,
csrfToken: req.csrfToken(),
allowAjax: true
});
});
}
router.get('/json/:id', function (req, res) {
var ids = req.params.id.match(RegExp(idpattern, 'img'));
if (ids) {
var searchSchema = Document;
var q = {};
q[idpath] = {
"$in": ids
};
searchSchema.find(q, {
//body: 1,
_id: 0
}, {}, function (err, docs) {
if (err) {
res.json({
title: 'Error',
message: 'Query failed',
docs: []
});
} else {
res.json(docs);
}
});
} else {
res.json([]);
}
});
router.post('/json/', async function (req, res) {
if (req.body.ids && req.body.ids.length > 0) {
//console.log('REQ: ' + JSON.stringify(req.body.ids));
var q = {};
q[idpath] = {
"$in": req.body.ids
};
var fields = {
_id: 0
};
if(req.body.fields && req.body.fields.length > 0) {
for (var f of req.body.fields) {
fields[f] = 1;
}
}
var results = await Document.find(q, fields);
res.json(results);
} else {
res.json([]);
}
});
var checkID = module.checkID =
check(jsonidpath)
.exists()
.custom((val, {
req
}) => {
if (validator.matches(val, '^' + idpattern + '$')) {
return true;
}
return false;
})
.withMessage('Document ID not valid. Expecting ' + idpattern);
var existCheck = module.existCheck = check(jsonidpath)
.exists()
.custom((val, {
req
}) => {
var q = {};
q[idpath] = val;
return Document.findOne(q).then((doc) => {
if (doc) {
throw new Error('Document ' + val + ' exists. Save with a different ID or Update the existing one');
return false;
} else {
return true;
}
});
});
var random_slug = function () {
return crypto.randomBytes(13).toString('base64').replace(/[\+\/\=]/g, '-');
}
var matchingEmail = async function (doc_id) {
try{
return await Document.db.collection('mails').find({
'$text': {
'$search': '"' + doc_id + '"'
}
}, {
'author': 1,
'subject': 1,
'hypertext': 1,
// 'html': 1,
'createdAt': 1,
_id: 1
}).toArray();
} catch(e) {
return [];
}
};
var unifiedComments = async function(doc_id, comments) {
var emails = null;
//var emails = await matchingEmail(doc_id);
//console.log('GOT emails' + emails);
var u = [];
if(emails) {
u = u.concat(emails);
}
if(comments) {
u = u.concat(comments);
}
u.sort(function(a, b) {return b.createdAt - a.createdAt;});
return u;
}
var addComment = async function (doc_id, username, text, parent_slug) {
try {
//var posted = new Date();
var slug = random_slug();
var q = {};
q[idpath] = doc_id;
//console.log('Commenting on ' + doc_id + ' q=' + JSON.stringify(q))
var dt = new Date();
var ret = await Document.findOneAndUpdate(
q, {
$push: {
comments: {$each: [{
createdAt: dt,
updatedAt: dt,
author: username,
slug: slug,
hypertext: text,
}], $position: 0
}
}
}, {new: true}).exec();
return ({
ok: 1,
ret: await unifiedComments(doc_id, ret ? ret.comments :[]),
});
} catch (e) {
console.log(e);
return ({
msg: e
});
}
}
var updateComment = async function (doc_id, username, text, slug, date) {
try {
var q = {};
q[idpath] = doc_id;
q['comments.slug'] = slug;
q['comments.author'] = username;
var ret = await Document.findOneAndUpdate(q, {
'$set': {
"comments.$.hypertext": text,
"comments.$.updatedAt": date
}
}, {
new: true
}).exec();
return ({
ok: 1,
ret: await unifiedComments(doc_id, ret ? ret.comments : [])
});
} catch (e) {
//console.log(e);
return ({
msg: e
});
}
}
router.post('/comment', csrfProtection, async function (req, res) {
if (req.body.slug) {
var r = await updateComment(req.body.id, req.user.username, req.body.text, req.body.slug, new Date());
res.json(r);
} else {
addComment(req.body.id, req.user.username, req.body.text).then(r => {
res.json(r);
})
}
});
var getSubDocs = async function (subSchema, doc_id) {
var q = {}
q[idpath] = doc_id;
parentDoc = await Document.findOne(q).exec();
if (parentDoc) {
var subq = {
parent_id: parentDoc._id
}
var ret = await subSchema.find(subq, {
_id: 0,
parent_id: 0
}).sort({
updatedAt: -1
}).exec();
return (ret);
} else {
return {
'message': 'No parent document'
};
}
}
/*
router.get('/comment/:id(' + idpattern + ')', async function (req, res) {
var q = {};
q[idpath] = req.params.id;
var ret = await Document.findOne(q, {comments: 1}).exec();
var emails = await Document.db.collection('mails').find({'$text':{'$search': '"' + req.params.id + '"'}},{'author':1,'subject':1,'body':1,'html':1,'createdAt':1,_id:0}).toArray();
//res.json(ret ? ret.comments.sort(function(a, b) {return a.createdAt < b.createdAt;}) : []);
//console.log(emails);
res.json(unified);
});
*/
router.get('/log/:id(' + idpattern + ')', function (req, res) {
getSubDocs(History, req.params.id).then(r => {
res.json(r);
});
});
var deep_value = function (obj, path) {
var ret = obj;
for (var i = 0, path = path.split('.'), len = path.length; i < len; i++) {
ret = ret[path[i]];
if (ret === undefined) {
break;
}
};
//console.log(' = ' + ret);
return ret;
};
if(opts.conf.files) {
router.post('/:id(' + idpattern + ')/file', csrfProtection, async function (req, res) {
var fq = {};
fq[idpath] = req.params.id;
var doc = await Document.findOne(fq);
if(doc) {
var fcount = 0;
var comment;
var busboy = new Busboy({
headers: req.headers
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
if (fieldname=='comment') {
comment = val;
}
});
busboy.on('file', async function (fieldname, file, filename, encoding, mimetype) {
var x = fcount++;
//console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype + ' COMMENT: '+ comment);
//var base = opts.conf.files;
var collectionDir = opts.conf.files; //path.join(base, req.baseUrl);
if (!fs.existsSync(collectionDir)) {
fs.mkdirSync(collectionDir);
//console.log(' Created collection dir' + collectionDir);
}
var docDir = path.join(collectionDir, req.params.id);
if (!fs.existsSync(docDir)) {
fs.mkdirSync(docDir);
//console.log(' Created Doc dir' + docDir);
}
docDir = path.join(docDir, 'file');
if (!fs.existsSync(docDir)) {
fs.mkdirSync(docDir);
//console.log(' Created Doc dir' + docDir);
}
var saveTo = path.join(docDir, path.basename(filename));
var pn = path.normalize(saveTo);
if (pn.startsWith(docDir)) {
var w = await file.pipe(fs.createWriteStream(pn));
w.on('finish', async function(){
var fileq = {};
fileq[idpath] = req.params.id;
fileq['files.name'] = filename;
//console.log('Update query'+ JSON.stringify(fileq));
var [ftype, fsubtype] = mimetype ? mimetype.split('/',2) : ['unknown','unknown'];
; var nf = {
"name": filename,
"updatedAt": new Date(),
"size": w.bytesWritten,
"comment": comment,
"user": req.user.username,
"type": ftype,
"subtype": fsubtype
};
var ret = await Document.findOneAndUpdate(fileq, {
'$set': {
"files.$": nf
}
}, {
new: true
}).exec();
if(ret === null) {
var ret = await Document.findOneAndUpdate(fq, {
$push: {
files: nf
}
}, {
new: true
}).exec();
}
if(x==(fcount-1)) {
if(busboy._done) {
res.json({
ok: '1',
//flist: flist
})
} else {
busboy.on('finish', function(){
res.json({
ok: '1',
//flist: flist
})
});
}
}
});
} else {
res.json({
ok: 0,
msg: 'Invalid file path!'
});
}
});
/*busboy.on('finish', function () {
res.json({
ok: '1',
//flist: flist
})
});*/
req.pipe(busboy);
} else {
res.json({
ok: 0,
msg: 'Document not found!'
});
}
});
router.get('/:id(' + idpattern + ')/file/:filename',
async function(req, res, next) {
res.setHeader("Content-Security-Policy", "default-src 'none'; connect-src 'none'");
return next();
},
express.static(path.join(opts.conf.files))
);
router.delete('/:id(' + idpattern + ')/file/:filename',async function (req, res) {
var fq = {};
fq[idpath] = req.params.id;
try {
var ret = await Document.update(fq,{$pull: {files: {name: req.params.filename}}});
res.json({ok:ret.ok, n:ret.n});
} catch(e) {
res.json(e);
}
});
router.get('/files/:id(' + idpattern + ')',
async function(req, res, next) {
res.setHeader("Content-Security-Policy", "default-src 'none'; connect-src 'none'");
return next();
},
async function (req, res) {
var fq = {};
fq[idpath] = req.params.id;
var doc = await Document.findOne(fq,{files:1});
res.json(doc.files);
});
router.get('/:id(' + idpattern + ')/file/', function (req, res) {
fs.readdir(path.join(opts.conf.files, req.params.id, '/file/'), function (err, items) {
res.render(opts.list, {
title: req.params.id + ' files',
docs: items ? items.map(x => {
return ({
'File': x,
'Filetype': x.substr(x.lastIndexOf('.') + 1)
})
}) : [],
columns: ['File', 'Filetype'],
subtitle: 'Attachments for ' + req.params.id
});
});
});
}
router.post('/update',
csrfProtection,
function(req, res, next) {req.query=req.body; next();},
querymen.middleware(qSchema),
async function (req, res) {
try {
var q = req.querymen.query;
var f = q[idpath];
if(f) {
delete q[idpath];
for(k in q) {
if (q[k] === "") {
delete q[k]
}
}
if (Object.keys(q).length != 0) {
var d = new Date();
q.author = req.user.username;
q.updatedAt = d;
//console.log(q);
var fq = {};
fq[idpath] = f;
var docs = await Document.find(fq);
var results = [];
for(var d of docs) {
var result = await Document.findAndModify({
_id: d._id
}, [], {
"$set": q,
"$inc": {
__v: 1
}
}, {
"upsert": false,
"new": true
});
var r = module.addHistory(d, result.value);
if(r) {
r.__v = r.__v + ' ('+deep_value(result.value, idpath)+')';
results.push(r);
}
//results.push(deep_value(result.value, idpath));
}
//console.log(results);
res.render('changes', {
// renderTemplate: 'changes',
textUtil: textUtil,
title: 'Bulk update results',
docs: results
});
} else {
res.render('blank', {
title: 'Error',
message: 'Error: No updates specified! Please select fields and values to update.'
});
}
} else {
res.render('blank', {
title: 'Error',
message: 'Error: No items selected. Please select one or more items to update'
});
}
} catch (err) {
req.flash('error', err);
res.render('blank', {
title: 'Error',
message: 'failed bulk updates: ' + err.message
});
}
});
//check if Document ID exists, insert, then redirect to Document ID page
if (!opts.conf.readonly) {
router.post(/\/(new)$/, csrfProtection, [checkID, existCheck], module.createDoc);
// update or submit new Document ID
router.post('/:id(' + idpattern + ')', csrfProtection, [checkID], module.upsertDoc);
router.delete('/:id(' + idpattern + ')', csrfProtection, function (req, res) {
let query = {};
query[idpath] = req.params.id;
Document.remove(query, function (err) {
if (err) {
res.send('Error Deleting');
return;
} else {
res.send('Deleted');
}
});
});
// load Document editor form
}
router.get('/list/',
querymen.middleware(qSchema),
async function (req, res) {
var r = await Document.aggregate([
{ $match: req.querymen.query },
{ $project: project }
]);
res.json(r);
});
router.get('/examples/',
querymen.middleware(qSchema),
async function (req, res) {
//console.log(JSON.stringify(req.querymen.query));
var r = await Document.find(req.querymen.query).distinct(req.query.field);
res.json({examples:r});
});
router.get('/agg/',
querymen.middleware(qSchema),
async function (req, res) {
if (req.query.f) {
var f = req.query.f;
if (!Array.isArray(f)) {
f = [f];
}
var pipeLine = normalizeQuery(req.querymen.query);
var prj = {};
for(var k of f) {
var options = opts.facet[k];
if(options) {
if (Array.isArray(options.path)) {
prj[k] = { "$setUnion": [options.path.map(x => {return '$' + x})] }
} else if (typeof options.path === 'string') {
prj[k] = '$' + options.path;
} else if(Object.keys(options.path).length != 0) {
prj[k] = options.path;
}
}
}
if (Object.keys(prj).length > 0) {
var g = {},
gg = {};
if (f.length == 1) {
g = '$' + f[0];
} else {
for (var k of f) {
g[k] = '$' + k;
gg[k] = '$_id.' + k;
}
}
pipeLine = pipeLine.concat([{
$project: prj
}, {
$group: {
_id: g,
t: {
$sum: 1
}
}
}
]);
gg.t = '$t';
if (f[1] && !req.query.ungroup) {
delete gg[f[0]];
pipeLine.push({
$group: {
_id: '$_id.' + f[0],
t: {
$sum: '$t'
},
items: {
$push: gg
}
}
})
}
if (req.querymen.cursor.sort) {
pipeLine.push({
$sort: {
'_id': 1
}
})
}
//console.log('pipeLine:' + JSON.stringify(pipeLine,2,2,2));
var ret = await Document.aggregate(pipeLine);
res.json(ret);
} else {