-
Notifications
You must be signed in to change notification settings - Fork 1
/
database.js
86 lines (72 loc) · 2.08 KB
/
database.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
require('dotenv').config();
const mongoose = require('mongoose');
const MONGO_URI = process.env.MONGO_URI;
mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
const Schema = mongoose.Schema;
const CounterSchema = Schema({
_id: {type: String, required: true},
seq: { type: Number, default: 0 }
});
const Counter = mongoose.model('counter', CounterSchema);
const answerSchema = new Schema({
answerText: {
type: String,
required: true
},
isCorrect: {
type: Boolean,
default: false
},
image: {
type: String
}
}, {_id: false});
answerSchema.index({ answerText: 'text'});
const questionSchema = new Schema({
_id: Number,
question: {
type: String,
required: true
},
answers: {
type: [answerSchema],
required: true,
validate: [(value) => {
return value.length > 1 && value.filter((el) => el.isCorrect).length === 1
}, "Must be only 1 correct"]
},
tags: [String],
subject: {
type: String,
required: true
},
source: String
});
questionSchema.index({ question: 'text', subject: 'text', tags: 'text'});
questionSchema.pre('save', function(next) {
var doc = this;
Counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1} }, {useFindAndModify: false, new: true, upsert: true}, function(error, counter) {
if(error) {
console.error(error)
return next(error);
}
doc._id = counter.seq;
next();
});
});
questionSchema.pre('insertMany', function(next) {
var doc = this;
console.log(doc._id)
next()
// Counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1} }, {useFindAndModify: false, new: true, upsert: true}, function(error, counter) {
// if(error) {
// console.error(error)
// return next(error);
// }
// doc._id = counter.seq;
// next();
// });
});
const Answer = new mongoose.model('Answer', answerSchema);
const Question = new mongoose.model('Question', questionSchema)
module.exports = {Question, Counter}