我掙扎從最近2小時更新我的嵌套集合。有人可以嘗試引導我正確的方向嗎?更新嵌套的查詢在貓鼬
var ChoiceSchema = new Schema ({
body: {type: String, required: true},
correct: {type: Boolean, required: true},
timesDisplayed: {type: Number, default: 0},
timesSelected: {type: Number, default: 0},
images: {}
});
var QuestionSchema = new Schema({
contentId: {type: String, required: true},
questionBody: {type: String, required: true},
timesAnswered: {type: Number, default: 0},
timesCorrect: {type: Number, default: 0},
timesIncorrect: {type: Number, default: 0},
timesSkipped: {type: Number, default: 0},
explanation: {
contentId: {type: String, required: true},
body: {type: String, required: true},
images: {}
},
images: {},
choices: [ChoiceSchema]
});
var ExamSchema = new Schema ({
subject: {type: String, required: true},
dateCreated: { type: Date, default: Date.now },
examNumber: Number,
section1: {
part1: {
timeInMinutes: Number,
instructions: {type: String, required: true},
questions: [QuestionSchema]
},
part2: {}
},
section2: {}
});
我正在嘗試更新QuestionsSchema
中的timesAnswered
屬性。
Exam.findById(req.params.id, function (err, exam) {
var ids=JSON.parse(req.body.ids);
if(err) { return handleError(res, err); }
if(!exam) { return res.send(404); }
if(ids.length) {
for(var i=0;i<ids.length;++i){
Exam.update({'section1.part1.questions.$._id':ids[i]},
{ $set: {
'section1.part1.questions.$.timesAnswered': 1 // <== and here
}}, function (err, numAffected) {
if(err) throw err;
}
);
}
}
return res.json(exam);
});
其中IDS是包含數組的問題ID
[ '54db8ee6529b197018822eb4',
'54db8ee6529b197018822ea7',
'54db8ee6529b197018822ea0' ]
我引用這個問題,但我不知道爲什麼它不適合我的工作了。 Mongoose nested document update failing?
'Exam.update'是異步的,所以當你調用'回報res.json(考試)','的對象exam'沒有更新呢。 – 2015-02-11 18:03:57
@RodrigoMedeiros即使我只是用'return true'替換它,那麼它也行不通。所以我不能理解最新的錯誤。 – 2015-02-11 18:07:29
究竟是什麼錯誤?有錯誤嗎? – 2015-02-11 19:19:06