-
Notifications
You must be signed in to change notification settings - Fork 0
/
studentprovider.js
77 lines (67 loc) · 2.19 KB
/
studentprovider.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
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
StudentProvider = function(host, port) {
this.db= new Db('node-mongo-student', new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
// getCollection
StudentProvider.prototype.getCollection= function(callback) {
this.db.collection('students', function(error, student_collection) {
if( error ) callback(error);
else callback(null, student_collection);
});
};
// findAll
StudentProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, student_collection) {
if( error ) callback(error)
else {
student_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
// findByRollNumber
StudentProvider.prototype.findByRollNumber = function(roll_number, callback) {
this.getCollection(function(error, student_collection) {
if(error) callback(error)
else {
student_collection.findOne({roll_number:roll_number}, function(error, result) {
if(error) callback(error)
else {
callback(null, result);
}
});
}
});
}
// save
StudentProvider.prototype.save = function(students, callback) {
this.getCollection(function(error, student_collection) {
if( error ) callback(error)
else {
if( typeof(students.length)=="undefined") {
students = [students];
}
for(var i=0; i<students.length; i++){
var student = students[i];
// Check if any of the students have the same roll number, then update them
this.findByRollNumber(students[i].roll_number, function(error, st) {
if(st.length)
})
student.created_at = new Date();
student.total = Number(student.maths) + Number(student.science) + Number(student.social_sciences) + Number(student.english);
student.percentage = Number((student.total / 4));
}
student_collection.insert(students, function() {
callback(null, students);
});
}
});
};
exports.StudentProvider = StudentProvider;