gpt4 book ai didi

node.js - 更新 Mongoose 中的嵌套查询

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:20 24 4
gpt4 key购买 nike

过去 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?

最佳答案

您的代码有两个问题。

首先,如 @yazarubin指出,您的更新条件有一个不必要的 $,因此只需将其删除:

Exam.update({'section1.part1.questions._id':id},

其次,您正在标准 for(同步)内运行更新任务(异步任务),因此它不会等待更新任务完成。在这种情况下,您可以使用async.each功能:

var async = require('async'); // be sure to install and require the async module

async.each(ids, function (id, callback) {
Exam.update({'section1.part1.questions._id':id},
{ $set: {
'section1.part1.questions.$.timesAnswered': 1 // <== and here
}}, function (err, numAffected) {
if(err) throw err;
callback();
}
);
}, function (error) {
if (error) res.send(500);
res.send(exam); // send the response just when all tasks has finished
});

,或者您可以使用某种 Promise 库来完成相同的任务。

关于node.js - 更新 Mongoose 中的嵌套查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28460813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com