【发布时间】:2018-07-17 02:31:33
【问题描述】:
我正在尝试从数据库中取出文档(问题)并将它们存储在一个数组中以供进一步使用(问题将被询问给玩家)。
但是,当我调用 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 数组是一个字段变量,但它似乎最终被清除了。
感谢任何帮助!
【问题讨论】:
标签: arrays node.js mongodb typescript mongoose