Tuesday 6 February 2018

Why is the array I edit from a mongoose callback empty after it is done?

I am trying to get documents out of the database (questions) and store them in an array for further use (The questions would be asked to the players).However, when I call findOne(), and add it's result to an array, the array is empty after the callback.. Even though it contains the data in the callback!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; } This is the code that loads the documents, and saves their content in the array.Any help with this? I'm absolutely lost with this, as it shouldn't be about some kind of scope error. The Questions array is a field variable, but it seems to get cleared in the end.

Submitted February 06, 2018 at 10:23PM by SixLiabilities

No comments:

Post a Comment