0

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 ?

1 Answers1

0

Just a tip, change if (result) for if (result.length) because a empty object (Array) returns true.

And to execute the query async, see this answer.

Community
  • 1
  • 1
andergtk
  • 410
  • 4
  • 7
  • Actually I have added a unique:true to the eventId field so if any game with same eventId is available it is not pushed into the db. But is it a bad practice. – srikanth chitturi Jun 05 '16 at 14:26