This repository was archived by the owner on Sep 1, 2022. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathdatabase.js
More file actions
101 lines (79 loc) · 2.02 KB
/
Copy pathdatabase.js
File metadata and controls
101 lines (79 loc) · 2.02 KB
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
/* eslint-disable indent */
const mongoose = require('mongoose');
// connect to the database
const db = process.env.DATABASE;
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
console.log('MongoDB connected...');
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
connectDB();
// define the grade user schema
const GradeSchema = new mongoose.Schema({
tag: {
type: String,
required: true,
},
gradeCheckpoints: {
type: Array,
},
averageScore: {
type: Number,
default: 0,
},
});
const Grade = mongoose.model('grade', GradeSchema);
// define functions
const addUser = async (tag) => {
// creates a new grade object for a new user, if they don't already have a grade object
// tag = a string, their discord tag
// returns true if successful, false if failed
let grade = await Grade.findOne({ tag });
if (!grade) {
grade = new Grade({
tag,
gradeCheckpoints: [],
});
await grade.save();
return true;
} else {
return false;
}
};
const addCheckpoint = async (tag, grades) => {
// add a grade checkpoint to the checkpoint list
// tag = discord tag of the user, grades = array of the numerical grade values
// returns true if succeeded, false if failed
const grade = await Grade.findOne({ tag });
if (!grade) {
return false;
} else {
const toPush = {
percentages: grades,
// the current date doesnt work yet for some reason
date: new Date(),
};
const gradeCheckpoints = grade.gradeCheckpoints;
gradeCheckpoints.push(toPush);
await Grade.findOneAndUpdate(
{ tag },
{ $set: { gradeCheckpoints } },
{ useFindAndModify: false }
);
return true;
}
};
const getUser = async (tag) => {
// return an user as an object, given their tag
return Grade.findOne({ tag }).exec();
};
// export functions
module.exports = { addUser, addCheckpoint, getUser };