JJuOn

Implement models/challenge.js

1 +const mongoose = require("mongoose");
2 +
3 +const { Schema }=mongoose;
4 +
5 +const GroupSchema=new Schema({
6 + members:{type:[String]},
7 +});
8 +
9 +const ChallengeSchema=new Schema({
10 + challengeName: {type: String, required: true},
11 + startDate: {type: Object, required: true},
12 + endDate: {type: Object, required: true},
13 + durationPerSession: {type: String, required: true}, // '1d' means one day per session, '2w' means 2 weeks per session, '3m' means 3 months per session.
14 + goalPerSession: {type: Number, required:true}, // number of problems for one session
15 + groups:{type: [GroupSchema], required:true}, // groups attending challenge, group of only one member supposed to be single
16 +});
17 +
18 +ChallengeSchema.statics.findByChallengeName=function(challengeName){
19 + return this.findOne({challengeName:challengeName});
20 +}
21 +
22 +ChallengeSchema.methods.addNewGroup=function(group){
23 + this.groups.push(group);
24 + return this.save();
25 +}
26 +
27 +ChallengeSchema.methods.removeGroup=function(group_id){
28 + const idx=this.groups.findIndex((item)=>item._id===group_id);
29 + this.groups.splice(idx,1);
30 + return this.save();
31 +}
32 +
33 +ChallengeSchema.methods.getChallengeName=function(){
34 + return this.challengeName;
35 +}
36 +
37 +ChallengeSchema.methods.getStartDate=function(){
38 + return this.startDate;
39 +}
40 +
41 +ChallengeSchema.methods.getEndDate=function(){
42 + return this.endDate;
43 +}
44 +
45 +ChallengeSchema.method.getDurationPerSession=function(){
46 + return this.durationPerSession;
47 +}
48 +
49 +ChallengeSchema.methods.getGoalPerSession=function(){
50 + return this.goalPerSession;
51 +}
52 +
53 +ChallengeSchema.methods.getGroups=function(){
54 + return this.groups;
55 +}
56 +
57 +ChallengeSchema.methods.serialize=function(){
58 + return this.toJSON();
59 +}
60 +
61 +const Challenge=mongoose.model('Challenge',ChallengeSchema);
62 +module.exports=Challenge;
...\ No newline at end of file ...\ No newline at end of file