-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathmodel.js
More file actions
45 lines (37 loc) · 1.02 KB
/
model.js
File metadata and controls
45 lines (37 loc) · 1.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
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const sortAnswers = (a, b) => {
if (a.votes === b.votes) {
return b.updatedAt - a.updatedAt;
}
return b.votes - a.votes;
};
const AnswerSchema = new Schema({
text: String,
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
votes: { type: Number, default: 0 }
});
AnswerSchema.method('update', function(updates, callback) {
Object.assign(this, updates, { updatedAt: new Date() });
this.parent().save(callback);
});
AnswerSchema.method('vote', function (vote, callback) {
if (vote === 'up') {
this.votes += 1;
} else {
this.votes -= 1;
}
this.parent().save(callback);
});
const QuestionSchema = new Schema({
text: String,
createdAt: { type: Date, default: Date.now },
answers: [AnswerSchema]
});
QuestionSchema.pre('save', function (next) {
this.answers.sort(sortAnswers);
next();
});
const Question = mongoose.model('Question', QuestionSchema);
module.exports.Question = Question;