-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.js
46 lines (38 loc) · 1.07 KB
/
models.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
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const sortAnswers = function(a, b) {
// - negative a before b
// 0 no change
// + positive a after 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