Hello I want to loop a list of games and find if any game is already inserted , if it is already present in database then skip , otherwise insert the new game into the database. Each game has an unique eventId which I am checking before inserting a new game.
My code is :
for (var i=0;i < gamesList.length;i++) {
var game = gamesList[i];
// check whether the game is already present in the DB.
Game.findOne({"eventId": game.ID},function(err,result){
if(err){
console.log(err);
res.json(err);
}
if(result){
console.log('game is already inserted skip');
}
else{
console.log('new game available insert this into list');
}
});
}
But the main problem here is , with asynchronous nature of the code , I guess. when Game.find is executed , it is not waiting for the results to come , it proceeds for the next game in the loop. The callback is invoked for only last game in the list , gamesList.length time . I want to find whether a game is already present in the database and then when the result comes want to go for the next game in the list . Please post any better solution where I can achieve this kind of functionality. What about using synchronous code does it blocks and disadvantageous ?