我创建了以下mongoose模式,用于在mongodb中保存测验 -
var answerSchema = new Schema({
answer: String,
correct: Boolean
});
var questionSchema = new Schema({
title: String,
tag: String,
chapterName: String,
marks: Number,
negativeMarks: Number,
correctAnswerExplanation: String,
hint: String,
answers: [answerSchema]
});
var quizSchema = new Schema({
courseId: Number,
courseName: String,
lectureId: Number,
lectureName: String,
popupTime: Number,
teacherName: String,
questions: [questionSchema]
});
var Quiz = mongoose.model('quiz', quizSchema );
我能够以下列方式存储硬编码值 -
var quiz1 = new Quiz({
courseId: 4,
lectureId: 5008,
popupTime: 3,
teacherName: 'Charles Xavier',
questions: [
{
"title": "Which is the Capital of India " ,
"answers": [
{ "answer": "Delhi", "correct": true },
{ "answer": "Bangalore", "correct": false },
{ "answer": "Mumbai", "correct": false },
{ "answer": "Chennai", "correct": false }
]
},
{
"title": "Where is facebook hosted? " ,
"answers": [
{ "answer": "Heroku", "correct": true },
{ "answer": "Digital Ocean", "correct": false },
{ "answer": "AWS", "correct": true },
{ "answer": "SWF", "correct": false }
]
}
]
});
quiz1.save(function(err, q) {
console.log("Saved ----");
console.log(q);
res.json(q);
});
这完全没问题。
现在,这是创建GUI表单的最佳方式,这样当用户填写详细信息时,它将转换为json,并通过mongoose保存在mongodb中。
我想出了以下表格 -
<form id="aj">
<input type="text" name="questions[0]" value="" placeholder="Question Title">
<input type="text" name="answers[0]" value="" placeholder="Answer 1">
<input type="text" name="answers[1]" value="" placeholder="Answer 2">
<input type="text" name="answers[2]" value="" placeholder="Answer 3">
<input type="text" name="answers[3]" value="" placeholder="Answer 4">
<button>Send</button>
</form>
在表单提交中,我使用此剪切序列化表单数据 -
var o = {};
var a = $( "#aj" ).serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
在快递路线处理程序中,我以类似的方式保存它 - 这是我通过快递 -
在请求正文中得到的内容{ questions: [ 'Q 1' ],
answers: [ ' A 1', 'A 2', 'A 3', 'A 4' ] }
var quiz = req.body(i.e the above object)
var add = new Quiz(quiz);
add.save(function(err, quiz) {
if(err) {
console.log(err);
} else {
console.log("Saved");
console.log(quiz);
}
});
但是我收到以下错误 -
[TypeError: Cannot use 'in' operator to search for '_id' in Q 1]
我如何解决这个问题,请帮助我刚开始使用mongodb和mongoose,我来自SQL背景。
另外,我应该如何设计一个表单,其中包含多个问题的输入,每个问题可以有多个答案,每个答案都有一点来表明答案是否正确。