aboutsummaryrefslogtreecommitdiff
path: root/node_simple.js
blob: d3eddb47a3c639cd78843add3efae38c5ccb062a (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
// a simple node driver to interact with mongo database

/* TO DO:
 * 1. get all exams given course code -- order by year desc ? DONE
 * 1B. get the title of the course ? DONE
 * 2. add upload date and user name  ? DONE
 * 3. remove exam ? DONE
 * 4a. get all questions for a given exam_id ? DONE
 * 4b. add exam id to each question returned. ? NO NEED
 * 6. get all solutions provided question_id and exam_id ? DONE
 * 5. solutions ? DONE -- need to add field for solutions provider, and updating. DONE
 * 7. add university field to courses, exams ? PENDING
 * 8. make a user ? DONE
 * 9. update user info when they comment or post a solution  ? PENDING
 * 10. comment_history ? DONE
 * 11. solutions_history ? DONE
 * 12. voting for solutions ? DONE
 * 23. A search users function ? DONE
 * 
 * */


/* I pass in exam id and you give me the number of questions and the comments and solutions associated with each question?*/

/* Tables SO FAR:
 * 1. exams
 * 2. courses
 * 3. solutions
 * 4. users
 * 5. logins
 *
 * */

/*Tables schema SO FAR:*/
// |======================================================exams==================================================================================|
// |_________ _id_____________|course_code|year__|term__|type____|instructors|page_count|questions_count|questions_list_|upload_date|uploaded_by_|
// |==========================|===========|======|======|========|===========|==========|===============|===============|===========|============|
// |"578a44ff71ed097fc3079d6e"|"CSC240"   |2016  |"fall"|"final" |["a","b"]  |20        | 10            |[{id,q},{id,q}]| "date"    | "by"       |
// |..........|


// |=======================courses=========================|
// |_________ _id_____________|course_code|title___________|
// |==========================|===========|================|
// |"178a42342233ff71c3079d6e"|"CSC240"   |"title"         |
// |..........|


// |================================solutions========================================================|
// |_________ _id_____________|exam_id_____________________|q_id_|text____|votes|comments   | author |
// |==========================|============================|=====|========|=====|===========|========|
// |"354ff71ed078933079d6467e"|"578a44ff71ed097fc3079d6e"  |1    |"answer"| 1   |[{},{}]    |  joe   |
// |..........|

// |========================================users===============================================================================|
// |_______ _id_________|email_________|user_name__|f_name__|l_name__|uni___|departm.|answered|messeges|comments|phone|followers|
// |====================|==============|===========|========|========|======|========|========|========|========|=====|=========|
// |"3.....efsdfsdf...."|blah@blah.com |"some_user"|"f.name"|"l.name"|"uofT"|CS      |40      |30      |15      |() - |[{},{}]  |
// |..........|

// |====================================login===================================|
// |_________ _id_____________|email____________|user_name|pass_________________|
// |==========================|=================|=========|=====================|
// |"askjdfklajsdf..........."|"asdf@asdf.com   |"asdfasd"|(some hasehd thing)  |
// |..........|

/*

NEW COLLECTIONS:

- sessions: stores user session - no need to keep track
- admins: stores admin name, username and password only. The logins collection will be reserved for user logins.

 */



var exports = module.exports = {};

const debug_mode = false;

Object.assign = require('object-assign');
var mongodb = exports.mongodb =  require('mongodb');
var mongoFactory = exports.mongoFactory = require('mongo-factory');
var ObjectId = require('mongodb').ObjectID;
var assert = require('assert');

// Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname
var uri = exports.uri =  'mongodb://general:assignment4@ds057862.mlab.com:57862/solutions_repo';


// Keep this for testing on local machine, do not remove. - Humair
//var uri = 'mongodb://localhost:27017/db';


//***********************PRELIMINARY TESTING******************************************|

/*refer to testImports.js*/

//****************************FUNCTIONS************************************************|

exports.search_users = function ( token, callback ) {

    mongoFactory.getConnection(uri).then(function (db) {
        var users = db.collection('users');
        users.createIndex(          // make the following fields searchable
            {
                "user_name":"text",
                "f_name":"text",
                "l_name":"text"
            });
        users.find(
            { $text: { $search: token } },
            { score: { $meta: "textScore" } }
        ).sort( { score: { $meta:"textScore" } } ).toArray(function (err, docs) {
            if (err) callback(false, "Error: some error while searhing");
            else {
                // console.log(docs);
                callback(true, docs);
            }
        });

        db.close();

    }).catch(function (err) {
        console.error(err);
    });
};


exports.followExam = function (user_name, exam_id, callback) {

    exports.retrieveFollows(user_name, function (bool, result) {
        if (!bool) console.log(result);
        else {      // no err occured so far...

            var found = false;
            for (var i = 0; i < result.length; i++) {       // search through the list of exams followed
                if (result[i] == exam_id) {
                    found = true;
                }
            }

            if (found) {    // means exam is already followed by user
                callback(false, "user is already following this exam");
            }

            else {      // add it to the user follower list
                mongoFactory.getConnection(uri).then(function (db) {

                    // find the user table
                    var users = db.collection('users');
                    // insert data into table
                    users.updateOne( {user_name: user_name}, {$push: {followers: exam_id}} , function (err) {
                        // if (err) throw err;
                        if (err) callback(false, "Error: some error occurred while following the exam");
                        else {
                            // console.log("user is following this exam");
                            callback(true, "Success: user is following this exam");
                        }
                    });
                    db.close();

                }).catch(function (err) {
                    console.error(err);
                });
            }
        }
    });
};


exports.retrieveFollows = function (user_name, callback) {

    mongoFactory.getConnection(uri).then(function (db) {

        // find the solutions table
        var users = db.collection('users');
        // insert data into table
        users.find( {user_name: user_name} ).toArray(function (err, docs) {
            // if (err) throw err;
            if (err) callback(false, "Error: followers could not be retrieved for some reason");
            else {
                callback(true, docs[0].followers);
            }
        });

        // db.close();
    }).catch(function (err) {
        console.error(err);
    });
};

// will add comments ASAP
/*  callback(success, data/message) => callback(boolean, object/String);
 *
 *
 */
exports.retrieve_userComments_history = function (username, callback) {

    // get a connection
    mongoFactory.getConnection(uri).then(function (db) {

        var solutions = db.collection('solutions');
        solutions.aggregate([

            { $match : {
                "comments.by": username
            }},
            { $unwind : "$comments" },
            { $match : {
                "comments.by": username
            }},
            {$project: {
                comment: "$comments.text",
                date: "$comments.date",
                exam_id: "$exam_id",
                _id: 0
            }}
        ]).toArray(function (err, results) {
            if (err) callback(false, "Error: some weird error occurred while query");
            else {
                callback(true, results);
            }

        });

        db.close();

    }).catch(function (err) {
        // console.err(err);
        callback(false, "Error: failed to connect to db");
    })
};

exports.retrieve_userComments_count = function (username, callback) {

    exports.retrieve_userComments_history(username, function (bool, results) {
        if (!bool) callback(false, "Error: error occurred");
        else {
            var length = results.length;
            callback(true, length);
        }
    });

};

exports.retrieve_userSolutions_history = function (username, callback) {

    // get a connection
    mongoFactory.getConnection(uri).then(function (db) {

        var solutions = db.collection('solutions');
        solutions.find( { author: username } ).toArray(function (err, result) {
            if (err) callback(false, "Error: problem while looking for stuff");
            else {
                callback(true, result);
            }
            db.close();
        });

    }).catch(function (err) {
        // console.err(err);
        callback(false, "Error: failed to connect to db");
    })
};

exports.retrieve_userSolutions_count = function (username, callback) {

    exports.retrieve_userSolutions_history(username, function (bool, results) {
        if (!bool) callback(false, "Error: error occured");
        else {
            var length = results.length;
            callback(true, length);
        }
    });

};


/*
 * This function creates and adds a user to users table.
 * IFF both the email and the user_name are not in the database already.
 * If either of them exist, the user is NOT added.
 * Params: fields - [email, user_name, f_name, l_name, uni, department, password, phone_num]
 * */
exports.add_user = function (fields, callbackUser) {
    console.log("inside add_user");
    // create a user object
    var user_data = {
        email: fields[0],
        user_name: fields[1],
        f_name: fields[2],
        l_name: fields[3],
        university: fields[4],
        department: fields[5],
        answered: 0,
        messages: 0,
        comments: 0,
        phone_num: fields[7],
        followers: []
    };

    var login_data = {
        email: fields[0],
        user_name: fields[1],
        password: fields[6]
    };

    // find out if this user already exists by checking their email
    exports.find_user( fields[0], function (result) {
        if  (result == false) {

            // find out if the user_name is taken
            exports.find_user_name( fields[1], function (docs) {
                if (docs == false) {        // if not ...
                    // continue
                    console.log("user name is valid");

                    // when both are valid add the user to the users and logins table
                    mongoFactory.getConnection(uri)
                        .then(function (db) {

                            var users = db.collection('users');
                            var logins = db.collection('logins');

                            // Add users, and login through callbacks
                            users.insertOne( user_data, function (err) {
                                if (err) {
                                    callbackUser(false, true, "Error : User has not been added.");
                                    db.close();
                                }

                                else {// user insert successfull
                                    logins.insertOne(login_data, function (err) {
                                        if (err) {
                                            callbackUser(false, true, "Error : User has not been added.");
                                            db.close();
                                        }

                                        else {// login insert successfull
                                            callbackUser(true, false, "User has been added.");
                                            db.close();
                                        }
                                    });
                                }
                            });

                        })
                        .catch(function (err) {
                            callbackUser(false, true,  "Unable to connect.");
                        })
                }
                else {
                    callbackUser(false, false, "Username is taken.");
                }
            });
        }
        else {
            callbackUser(false, false, "User with this email already exists.");
        }
    });
};

/*
 * This (helper) function returns true IFF user_name already exists in the database
 * Params: user_name - the user name
 * */
exports.find_user_name = function (user_name, callback) {
    // make a connection
    mongoFactory.getConnection(uri)
        .then(function (db) {

            var logins = db.collection('logins');
            logins.find( { user_name: user_name } ).toArray(function (err, result) {
                if (err) throw err;
                else if (result.length == 0) {  // nothing was found  so this user is new
                    callback(false);
                }
                else {
                    callback(true);
                }
            });
            // db.close();
        })
        .catch(function (err) {
            console.err(err);
        })
};

/*
  Retrieves the user object based on the username.
*/

exports.retrieveUser = function (username, callback) {

    mongoFactory.getConnection(uri).then(function (db) {
        var users = db.collection('users');

        users.find({user_name: username}).toArray(function (err, result) {
            if (err) {
                // callback(success, error, user, message)
                callback(false, true,  null, "Error : Could not retrieve user.");
            }

            else if (result.length) {
                console.log("retreive User: " + result[0]);
                callback(true, false, result[0], "User retrieved");
            }

            else {
                callback(false, false, null, "Username is undefined.");
            }

        });
    });
}

/*
 Returns the hashed password given the username. Assume username exists. Used for both admins and users.
 retrievePassword(String, boolean, function())
 */

exports.retrievePassword = function (username, callback) {
    mongoFactory.getConnection(uri).then(function (db) {

         var collection = db.collection('logins');

        collection.find({user_name: username}).toArray(function(err, result) {
            if (err) {
                // callback(success, password, message)
                callback(false, null, "Error : Could not retrieve password.");
            }

            else {
                console.log("NODE SIMPLE result[0]: " + result);
                var pwd = result[0].password; //result is an array
                callback(true, pwd, "Password retrieved");
            }
        });
    });
}

/*
 * This (helper) function returns true IFF email already exists in the database
 * */
exports.find_user = function (email, callback) {
    // make a connection
    console.log("inside find_user");
    mongoFactory.getConnection(uri)
        .then(function (db) {

            var logins = db.collection('logins');
            logins.find( { email: email } ).toArray(function (err, result) {
                if (err) throw err;
                else if (result.length == 0) {  // nothing was found  so this user is new
                    callback(false);
                }
                else {
                    callback(true);
                }
            });
            // db.close();
        })
        .catch(function (err) {
            console.err(err);
        })
};

// this function returns an array where is element contains info for a particular question
// such as the question number (_id), number of solutions (count), and number of comments
// (comments). [ {_id,count,comments}, {} ...]
exports.get_exam_info_by_ID = function (exam_id, callback) {

    mongoFactory.getConnection(uri)
        .then(function (db) {

            var solutions = db.collection('solutions');

            solutions.aggregate(
                [

                    // {$unwind: "$comments"},
                    { $match: { exam_id: exam_id }},
                    {
                        $project:
                        {
                            num_comments: { $size: "$comments" },
                            _id: "$exam_id",
                            q_id: "$q_id"
                        }
                    },
                    {
                        $group : {
                            _id : "$q_id",
                            count: { $sum: 1 },
                            comments: {$sum: "$num_comments"}
                            // num_comments: { $size: "$comments" }

                        }
                    }


                ]).toArray(function (err, result) {
                // console.log(result);
                callback(result);

            });
        })
        .catch(function (err) {
            console.err(err);
        })

};

/*
 * This function will add a comment to the solutions table
 * Params: sol_id - id of the solution to which to add the comment
 *         fields - [text, by_username]
 * */
exports.add_comment = function (sol_id, fields) {
    var Data = {
        text: fields[0],
        date: new Date(),
        by: fields[1]
    };

    mongoFactory.getConnection(uri)
        .then(function (db) {

            // find the solutions table
            var solutions = db.collection('solutions');
            // insert data into table
            solutions.updateOne( {_id: ObjectId(sol_id)}, {$push: {comments: Data}} , function (err, result) {
                if (err) throw err;
                else {
                    console.log("comment added");
                }
            });

        })
        .catch(function (err) {
            console.error(err);
        })
};

// get all solutions given an exam_id and the question number
exports.get_all_solutions = function (exam_id, q_num, callback) {
    mongoFactory.getConnection(uri)
        .then(function (db) {

            var solutions = db.collection('solutions');

            solutions.find(
                {
                    exam_id: exam_id,
                    q_id: q_num
                }
            ).toArray( function (err, docs) {
                if (err) throw err;
                else {
                    callback(docs);
                }
            });


        })
        .catch(function () {
            console.error(err);
        })
};

/*
 * This function will add a solution to the solutions table in the database .
 * Params: fields - [exam_id , question_id, solution text, user_name]
 * Note: exam_id - is a unique identifier for each exam in the database. to see an example, ...
 *          ... call get_all_exams and look at the output. Looks like: 578a44ff71ed097fc3079d6e
 *       question_id - is unique relevant to 1 exam.
 * */
exports.add_solution = function (fields, callback) {
    var Data = {
        exam_id: fields[0],
        q_id: fields[1],
        text: fields[2],
        votes: 0,
        comments: [],
        author: fields[3]
    };

    // establish a connection
    mongoFactory.getConnection(uri)
        .then(function(db) {

            // find the solutions table
            var solutions = db.collection('solutions');
            // insert data into table
            solutions.insert(Data, function(err) {
                if (err) callback(false , "Error: Failed to add the solution");
                else {

                    // console.log("solution added");
                    callback(true, "Success: added solution successfully!");
                    db.close(function (err) {   // close the connection when done
                        if (err) throw err;
                    });

                }
            });
        })
        .catch(function(err) {
            console.error(err);
        });

};




exports.vote_solution = function (sol_id, upORdown , callback) {
    var vote = (upORdown == "up") ? 1 : -1;

    mongoFactory.getConnection(uri).then(function (db) {
       var solutions = db.collection('solutions');
        solutions.updateOne(
            {_id: ObjectId(sol_id) },
            { $inc: { votes: vote} }, function (err) {
                // if (err) throw err;
                if (err) callback(false, "Error: couldnt update the vote count");
                else {
                    callback(true, "Success: updated vote count");
                }
        });
        db.close();
    }).catch(function (err) {
        console.log(err);
    });
};




/*
 * This function will retrieve all exams in the database given the course code ...
 * ... ordered by the year of the exam.
 * Params: course_code - an string of format "CSC309"
 * */
exports.get_all_exams = function (course_code, callback) {

    // get a connection
    mongoFactory.getConnection(uri)
        .then(function(db) {

            // get the exams table
            var exam_collection = db.collection('exams');

            // search exams table with given course code
            exam_collection.find(
                { course_code: course_code }
            ).sort({ year: -1}).toArray( function (err, docs) {   // order by year
                if (err) throw err;

                else {    // get the title
                    exports.find_course(course_code, function (result, data) {

                        if (result == true) {
                            // append the title from data to each exam object from docs
                            docs.forEach(function (doc) {
                                doc.title = data[0].title;
                            });

                            if (debug_mode == true){
                                console.log(docs);
                                console.log(data);
                            }
                            /*callback(docs);     // send back the data*/
                        }
                        else if (result == false) {    // no such course was found
                            console.log("This course has not been added to the database.");
                        }
                        callback(docs);     // send back the data

                    });
                }
            });
        })
        .catch(function(err) {
            console.error(err);
        });

};

/*
 * This function will add an exam to the database UNLESS the exams already exists.
 * If the exams table is empty, this will create one and then add the data.
 * Note: this assumes that (course_code + year + term + type) together form a unique exam.
 * i.e there can't be two exams occurring for the same course in the same year in the same term with the same type.
 * Params: fields - an array of format ["course_code", year, "term",
 *                 ["instructor1",...,"instructor n"], page_count, question_count
 *                 "upload_date", "user_name"]
 *         questions_array - a array by format ["q_1", "q_2", ... , "q_question_count"]
 *
 * callback parameter takes a boolean to indicate whether insert was successful
 * and an output status message.*/
exports.add_exam = function (fields, questions_array, serverCallback) {

    // construct an exam object
    var Data =
    {
        course_code: fields[0],
        year: fields[1],
        term: fields[2],
        type: fields[3],
        instructors: fields[4],
        page_count: fields[5],
        questions_count: fields[6],
        questions_list: [],
        upload_date: fields[7],
        uploaded_by: fields[8]
    };

    // create the questions objects
    for (var i = 1; i <= Data.questions_count; i++) {
        Data.questions_list.push(
            {
                q_id: i,
                question: questions_array[i - 1]
            }
        );
    }

    // first see if the exam already exists
    // pass in course_code, year, term and type...
    exports.find_exam([fields[0], fields[1], fields[2], fields[3]], serverCallback, function(result, serverCallback) {

        if (result == true) {     // meaning that the exam was found
            serverCallback(false, "This exam already exists in the database.");
            console.log("This exam already exists in the database");
        }

        else {    // add Data to the database
            // make a connection
            mongoFactory.getConnection(uri)
                .then(function(db) {

                    // find the exams table
                    var exam_collection = db.collection('exams');
                    // insert data into table
                    exam_collection.insert(Data, function(err) {
                        if (err) {
                            serverCallback(false, "Error: Could not add exam into database.");
                            throw err;
                        }
                        else {
                            console.log("exam added");
                            serverCallback(true, "Exam Successfully added.");
                            db.close(function (err) {   // close the connection when done
                                if (err) throw err;
                            });
                        }
                    });
                })
                .catch(function(err) {
                    serverCallback(false, "Error: Could not establish connection with database.");
                    console.error(err);
                });
        }
    });
};

/*
 * This function will return TRUE if the provided exam info already exists in the database
 * OR FALSE if it does not exist in the database.
 * Params: fields - an array of format ["course_code", year, "term", "type"]
 *
 * */
exports.find_exam = function (fields, serverCallback, callback) {

    var course_code = fields[0];
    var year = fields[1];
    var term = fields[2];
    var type = fields[3];

    // console.log(Data);

    // check the data to see if this exam exists...

    // first make a connection
    mongoFactory.getConnection(uri)
        .then(function(db) {

            // fetch the exams table
            var exams = db.collection('exams');

            // look for the exam
            exams.find(
                {
                    course_code: course_code,
                    year: year,
                    term: term,
                    type: type
                }
            ).toArray(function (err, docs) {
                if (err) throw err;

                if (docs.length == 0) { // if this exam doesnt exist.... add it
                    callback(false, serverCallback);
                }
                else {  // exam was found
                    callback(true, serverCallback);
                }
            });

            /*      db.close(function (err) {
             if (err) throw err;
             });*/

        })
        .catch(function(err) {
            console.error(err);
        });
};

/*
 * This function will add a course to the database UNLESS the course already exists.
 * If the course table is empty, this will create one and then add the data.
 * Note: this assumes that (course_codes) are unique.
 * Params: course_code - an string of format "CSC309"
 *         title - the course description
 * */
exports.add_course = function (course_code, title, serverCallback) {

    var courseData = {
        course_code: course_code,
        title: title
    };

    exports.find_course(course_code, function (result) {

        if (result == true){
            serverCallback(false, "Course already exists");
            console.log("course already exists");
        }
        else if (result == false) {    // add it
            mongoFactory.getConnection(uri)
                .then(function(db) {

                    // find the exams table
                    var courses = db.collection('courses');
                    // insert data into table
                    courses.insert(courseData, function(err) {
                        if (err) throw err;
                        else {
                            console.log("course added");
                            serverCallback(true, "Course added successfully.");
                            db.close(function (err) {   // close the connection when done
                                if (err) throw err;
                            });
                        }
                    });
                })
                .catch(function(err) {
                    console.error(err);
                });
        }
    });
};

/*
 * This function will return TRUE if the provided course info already exists in the database
 * OR FALSE if it does not exist in the database.
 * Params: course code - an string of the format: "CSC309"
 *
 * */
exports.find_course = function (course_code, callback) {
    // check the data to see if this exam exists...

    // first make a connection
    mongoFactory.getConnection(uri)
        .then(function(db) {

            // fetch the courses table
            var courses = db.collection('courses');

            // look for the courses
            courses.find(
                { course_code: course_code }
            ).toArray(function (err, docs) {
                if (err) throw err;
                // if this course doesnt exist.... add it (via add_course call)
                if (docs.length == 0) {
                    callback(false);
                }
                else {  // course was found
                    callback(true, docs);
                }
            });

            /*              db.close(function (err) {
             if (err) throw err;
             });*/

        })
        .catch(function(err) {
            console.error(err);
        });
};

/*
 * This function will remove the exam from the database given the combination of (course_code+ year +  term + type)
 * Params: fields - an array of format ["course_code", year, "term", "type"]
 *
 * */
exports.remove_exam = function (fields, serverCallback) {

    var course_code = fields[0];
    var year = fields[1];
    var term = fields[2];
    var type = fields[3];

    // establish connection
    mongoFactory.getConnection(uri)
        .then(function(db) {

            // fetch the exams table
            var exams = db.collection('exams');

            // look for the specific exam
            exams.removeOne(
                {
                    course_code: course_code,
                    year: year,
                    term: term,
                    type: type
                }, function (err, docs) {
                    if (err) throw err;
                    else {
                        if (docs.deletedCount == 1) {
                            serverCallback(true, "Exam was removed successfully");
                            db.close();
                            //console.log("exam was removed");
                        }
                        else if (docs.deletedCount == 0) {
                            serverCallback(false, "No such exam was found");
                            db.close();
                            //console.log("No such exam was found");
                        }
                    }
                }
            );
        })
        .catch(function(err) {
            console.error(err);
        });
};

// callback(success, error, data)
exports.get_exam_byID = function (id, callback) {

    // establish a connection
    mongoFactory.getConnection(uri)
        .then(function(db) {

            // find the solutions table
            var exams = db.collection('exams');
            // query
            exams.find( {_id: ObjectId(id)} ).toArray(function (err, docs) {
                if  (err) {
                    callback(false, true,  null);
                } else if (!docs) {
                    callback(false, false, null);
                }
                else {
                    callback(true, false,  docs[0]);

                }
            });
        })
        .catch(function(err) {
            callback(false, true, null);
        });
};


/******************************  ADMINS *********************************/

/*
 *   Adds an admin to the admins collection.
 *   Params: admin_data = {fname: firstname, lname: lastname, username: username, password: password}
 *   Callback: callback(success, error, message) => callback(boolean, boolean, String)
 */

exports.addAdmin = function (admin_data, callback) {
    console.log('addAdmin, admin_data: ' +  admin_data.fname);

    console.log("inside addAdmin");

    // Check if the admin username already exists. Also check for user username. If it does, then we don't add the admin_data and return a message.
    exports.adminExists( admin_data.username , function (error, exists, data, message) {
            console.log("adminExists: " + message);
            if (!exists && !error) {
                mongoFactory.getConnection(uri).then(function (db) {

                    var admins = db.collection('admins');

                    admins.insertOne( admin_data, function (err) {
                        if (err) {
                            callback(false, true, message);
                            db.close();
                        }
                        else {
                            callback(true, false, "Admin added.");
                            db.close();
                        }
                    });

                }).catch(function (err) {
                    callbackUser(false, true,  "Unable to connect.");
                })
            } else {
                callback(error, exists, message);
            }
    });

};


/*
 *  Equivalent of function find_user, but for admins. Calls back true if admin with a
 *  given username exists. If true, also returns the admin 'object'.
 *  Callback: callback(error, exists, message)
 */
exports.adminExists = function (username, callback) {
    // make a connection
    console.log("inside adminExists");
    mongoFactory.getConnection(uri).then(function (db) {

        var admins = db.collection('admins');
        admins.find( { username: username } ).toArray(function (err, result) {
            if (err) {
                callback(true, false, null, "Error: could not retrieve admin in adminExists().");
            } else if (result.length) {
                callback(false, true, result[0], "Admin with given username exists");
            } else {
                callback(false, false, null, "Admin with given username does not exist");
            }
        });
    })
    .catch(function (err) {
        callback(true, false, "Error: could not connect to the database.");
    })
};


/******************************  MAIL *********************************/

/*
 * mail_data = {
 *      sender: sender_username,
 *      receiver: receiver_username,
 *      message: message,
 *      date: date,
 * }
 *
 * callback(success, error, message)
 *
 */

exports.sendMail = function (mail_data, callback) {
    exports.find_user_name(mail_data.receiver, function (exist){
        if (exist) {
            mongoFactory.getConnection(uri).then(function(db) {
                var mail = db.collection('mail');

                mail.insertOne(mail_data, function(err) {
                    if (err) {
                        callback(false, true, 'Error: could not send message.');
                        db.close();
                    }
                    else {
                        callback(true, false, "Message sent.");
                        db.close();
                    }
                });
            });
        } else {
            callback(false, false, 'The receiver\'s  username is undefined.');
        }
    });
}


/*
 *
 * callback(success, error, data, message)
 * Returns the user's inbox (array of message objects)
 *
 */

exports.checkMailbox = function (username, callback) {

    mongoFactory.getConnection(uri).then(function(db) {

        var mail = db.collection('mail');

        mail.find({receiver: username}).toArray(function (err, data) {
            if (err) {
                callback(false, true, null, 'Error: could not retrieve inbox messages.');
            } else if (!data) {
                callback(false, false, null, 'No inbox.');
            } else {
                callback(true, false, data, 'Retrieved inbox');
            }
        });
    });

}

//testing
exports.findUserByID = function (id, callback) {
    // make a connection
    console.log("inside findUserByID");
    mongoFactory.getConnection(uri)
        .then(function (db) {
            var logins = db.collection('logins');
            logins.find( { _id : id }, function (err, result) {
                callback(err, result);
                db.close();
            });
        })
        .catch(function (err) {
            console.err(err);
        })
};




/*
 * userObj = {fs: fs, ls: ls, email: email, username: username, pass_hash: pass_hash, univ: univ, dept: dept}
 *
 *
exports.addUser = function (userObj) {
    mongoFactory.getConnection(uri)
        .then(function(db) {
            var users = db.collection('users').insertOne(userObj, function (err, result) {
                assert.equal(null, error);
                console.log("User inserted");
                db.close();
            });

        });
} */



/*    IGNORE BELOW *********************************************************************************



 /!*
 * Then we need to give Boyz II Men credit for their contribution
 * to the hit "One Sweet Day".
 *!/

 songs.update(
 { song: 'One Sweet Day' },
 { $set: { artist: 'Mariah Carey ft. Boyz II Men' } },
 function (err, result) {

 if(err) throw err;

 /!*
 * Finally we run a query which returns all the hits that spend 10 or
 * more weeks at number 1.
 *!/

 songs.find({ weeksAtOne : { $gte: 10 } }).sort({ decade: 1 }).toArray(function (err, docs) {

 if(err) throw err;

 docs.forEach(function (doc) {
 console.log(
 'In the ' + doc['decade'] + ', ' + doc['song'] + ' by ' + doc['artist'] +
 ' topped the charts for ' + doc['weeksAtOne'] + ' straight weeks.'
 );
 });

 // Since this is an example, we'll clean up after ourselves.
 songs.drop(function (err) {
 if(err) throw err;

 // Only close the connection when your app is terminating.
 db.close(function (err) {
 if(err) throw err;
 });
 });
 });
 }
 );
 });
 });*/