Correct approach in Mongoose - validating my code

Viewed 20

I have 3 collections in my application. Member - has a field called MemberMatches which is referencing the Matches collection. Tournament - has a field called TournamentMatches which is referencing the Matches collection Matches.

On the REACT front end on the click of a button, I am creating a bunch of matches using a for loop and making entries in the matches collection via node. At the time I want to enter the Object ID into the Member and Tournament collections.

Here is the code:-

for(i=0; i<playersList.length;){
      player1Name = playersList[i]
      for(j=0; j<playersList.length;){
        if(j<=i){
          j=i
          j++
          continue
        }
        player2Name = playersList[j]
        var newMatch = new MatchRegister({
          Player1Name: player1Name,
          Player1GroupNumber: groupNumber,
          Player2Name: player2Name,
          Player2GroupNumber: groupNumber,
        });newMatch.save(async function(err,data){
            if(err){
              console.log(err)
            } else {
              await Tournament.findOneAndUpdate({_id: tid}, {$push: {TournamentMatches: data._id}})
              await Member.findOneAndUpdate({MemberName: data.Player1Name}, {$push: {MemberMatches: data._id}})
              await Member.findOneAndUpdate({MemberName: data.Player2Name}, {$push: {MemberMatches: data._id}})
            }
        })
        j++
      }
      i++
    }
  }
  return

I am calling this function from the route.push. Saving the matches first and then 3 FindOneAndUpdate with the await keyword.

This entire code and functionality works. Upon execution I can clearly see that the data is being populated in all 3 collections correctly.

Question: Is this the right approach? Is there another Mongoose way to do this.

0 Answers
Related