Currently developing authentication using passportjs, express, mongodb.I had to do nested looping in order to check if username is already being used in multiple arrays. I have 3 for loops setup which is the problem. Whenever i sign up as new user (player in this case) it runs that code multiple times and signs up user twice/thrice with the same username but different ID of course, which is not what i want. I even have an if / else statement that checks if username is already used, but it ignores it.Here is the code:const game = await Game.findById(req.body.gameId); const allGames = await Game.find({}); const findPlayerUsername = await PlayerModel.find({username: req.body.username}); // Check if email is already used const existPlayer = await PlayerModel.find({}); if (existPlayer) { try { if (game.players !== undefined && game.players.length >= 1) { allGamesLoop: for (let i = 0; i < allGames.length; i++) { allGamesPlayersLoop: for (let j = 0; j < allGames[i].players.length; j++) { gamePlayersLoop: for (let k = 0; k < game.players.length; k++) { if (allGames[i].players[j].username !== req.body.username && game.players[k].username !== req.body.username) { console.log('Phase 1'); paHelper.registerPlayer(PlayerModel, passport, game, Game, req, res); } else if (allGames[i].players[j].username === req.body.username && game.players[k].username === req.body.username) { if (game.players[k].username === req.body.username) { console.log('Phase 2 NOTA'); res.json({message: 'Cannot have same username in the same game'}); } else if (game.players[k].username ``== req.body.username) { console.log('Phase 2'); paHelper.copyPastePlayer(findPlayerUsername, game, req, res); } } }; // For Loops }; }; } else { // Check if player doesn't exists if (findPlayerUsername.length === 0 || !findPlayerUsername[0].username) { console.log('Phase 3'); paHelper.registerPlayer(PlayerModel, passport, game, Game, req, res); // Check if players username is same as inserted username } else if (findPlayerUsername[0].username === req.body.username) { console.log('Phase 3.5'); paHelper.copyPastePlayer(findPlayerUsername, game, req, res); } } } catch (err) { throw new Error(err); } } else { res.json({message: 'Player Already Exists'}) } It kinda is a mess, because it has multiple conditional statements. Main problem is the first if statement in nested loops (phase 1). Though sometimes, code runs phase 3 and than phase 1 3 times.. which is not expected behaviour.
Submitted May 17, 2019 at 02:37PM by OMGitsBIP
No comments:
Post a Comment