[英]How to query findOne() in mongoose such that we get subset of array of documents which satisfy particular condition?
[英]The array gets cleared after mongoose.findOne()
我正在尝试从数据库中获取文档(问题)并将它们存储在数组中以备将来使用(问题将被问到播放器中)。
但是,当我调用findOne()并将其结果添加到数组时,回调之后该数组为空。即使它包含其中的数据,也是如此!
private Questions: iGeneralQuestion[];
private LoadQuestions(): iGeneralQuestion[] {
const result: iGeneralQuestion[] = [];
for (let qid of this.GeneralArguments.questionIds) {
QuestionModel.findOne({ id: qid }, (err: any, question: any) => {
if (err) return err;
if (!question) return question;
this.Questions.push({
questionId: question.id,
question: question.question,
answer: question.answer,
otherOptions: question.otherOptions,
timeLimit: question.timeLimit,
difficulty: question.difficulty
//explanation: question.explanation
//pictureId: question.pictureId
});
console.log(this.Questions); //The array is full here! (Gets filled with each iteration)
});
}
console.log(this.Questions); //But it doesn't contain anything here!
return result;
}
这是用于加载文档并将其内容保存在数组中的代码。
我尝试使用promise函数和find()而不是findOne()。。无济于事!
我对此完全迷失了,因为它不应该涉及某种范围错误。 Questions数组是一个字段变量,但最后似乎会清除它。
任何帮助表示赞赏!
当您调用QuestionModel.findOne({ id: qid }, (err: any, question: any) => {...});
,您正在注册一个回调函数,该函数将在找到文档后调用。 但是与此同时(当findOne(...)
查找文档时),其余代码将继续执行。
因此,在调用QuestionModel.findOne(...)
,for循环继续。 您尚未找到文档-这是在后台发生的。 最终,for循环将完成,并调用页面上的最后一个console.log(this.Questions)
,然后return result;
。 但是, findOne(...)
仍在后台查找文档。 它尚未找到任何内容,因此console.log(this.Questions)
不显示任何内容。 该数组在此时仍为空。 不久之后,在findOne(...)
最终找到文档之后,便调用了回调。
在处理如下异步代码时,可能值得研究一下promise:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
更多的优化方式(减少数据库操作)而不是查找每个记录,而是一次创建所有重新编码而不是创建结果。 希望这可以帮助 :)
private LoadQuestions(cb){
const result: iGeneralQuestion[] = [];
QuestionModel.find({
id: {
$in: this.GeneralArguments.questionIds // Array of all ids
}}, (err: any, questions: any) => {
if (err) cb(err);
questions.forEach((question) => {
if (question) {
result.push({
questionId: question.id,
question: question.question,
answer: question.answer,
otherOptions: question.otherOptions,
timeLimit: question.timeLimit,
difficulty: question.difficulty
//explanation: question.explanation
//pictureId: question.pictureId
});
}
});
return cb(null,result);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.