This is a function to search test questions and match the answer given by the user and stored in the database. Console.log() displays all 6 questions but in random order. And the value of num is 6 for each iteration. if I do console.log(num) without finding anything from the database then I correctly display values 1,2,3,4,5,6.
function(req,res){
var arr = [2,1,3,4,1,4],score=0, num=0;
Test.find({name:req.params.testnum}).
populate({
path: 'question',
model: 'Testques'
}).
exec(function(err,test){
console.log(test)
if(err){
res.status(500).send('DB error');
}
else{
arr.forEach(myFunction)
function myFunction(value){
num+=1;
Testques.find({Serialnum:num},function(err,ques){
console.log(num);
if(err){
console.log(err);
}
else{
console.log(ques);
console.log(ques[0].answer);
if(ques[0].answer == value){
score=score+4;
console.log(score);
}
}
})
}
}
})
}
Testques.findis an asynchronous process, butforEachis not. Sonum+=1will be executed all six times (once for each pass of theforEach) before any of yourTestques.findqueries have finished. So when they do finally finish,numis already at6.