[英]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.