-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquestion.js
104 lines (89 loc) · 2.5 KB
/
question.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const mongoose = require('mongoose');
const questionSchema = new mongoose.Schema({
author: {type: String},
type: {type: String},
data: {type: mongoose.Mixed}
});
questionSchema.statics.newQuestion = function (data, cb) {
// TODO this is problematic if two people create questions at the same time.
Question.getAll(questions => {
var new_question = new Question({
author: data.author,
type: data.type,
data: data
});
new_question.save(function (err) {
if (!err) {
cb(true);
} else {
console.log(err);
cb(false);
}
});
});
}
questionSchema.statics.getQuestion = function(id, cb) {
Question.findOne({_id: id}, (err,question) => {
if (!err && question) {
cb(true, question);
} else {
cb(false, null);
}
});
}
questionSchema.statics.update = function(body, cb) {
if (body.id == null) {
return cb(false);
}
Question.findOne({_id: body.id}, (err, question) => {
if (!err && question) {
if (body.author != null) {
question.author = body.author;
}
if (body.type != null) {
question.type = body.type;
}
question.data = body.data;
question.save(err => {
if (!err) {
cb(true);
} else {
cb(false);
}
});
} else {
cb(false);
}
});
}
questionSchema.statics.delete = async function(id, cb) {
Question.findOneAndDelete({_id: id}, { useFindAndModify: false }, (err, doc) => {
if (err) {
return cb(false);
} else{
return cb(true);
}
});
}
questionSchema.statics.getAll = function(cb) {
Question.find({}, (err, questions) => {
cb(questions);
});
}
questionSchema.statics.getAllAsync = async function() {
return Question.find({});
}
questionSchema.statics.getAllByAuthor = function(author,cb) {
Question.find({author: author}, (err, questions) => {
cb(questions);
});
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
module.exports = Question = mongoose.model('Question', questionSchema, 'questions');