My goal is to allow each user to choose a total of 6 players. When a player is selected, their player ID is sent to a node on the database called 'total' using the push() method. The code snippet is provided below:
var ref = firebase.database().ref().child('players');
var ref3 = firebase.database().ref().child('users').child(uid).child('total');
$scope.players = $firebaseArray(ref);
console.log($scope.players);
$scope.history = [];
$scope.buy = function(player) {
// Remove if already added locally
var index = $scope.history.indexOf(player);
if(index >= 0){
$scope.history.splice(index,1);
return;
}
// Remove if already added on firebase
// Max of 6 players allowed
if($scope.history.length >= 6){
alert('Max of 6 players allowed');
return;
}
var selected = $scope.history.reduce(function(a,b){
a[b.position] = (a[b.position] || 0) + 1;
return a;
}, {}) || {};
if(!selected[player.position] || selected[player.position] < 2){
$scope.history.push(player);
ref3.push(player.id);
}else{
alert('You can only add two players per position');
}
};
$scope.getTotal = function(){
return $scope.history.reduce(function(tot, p){
tot = tot - p.price;
return tot;
}, $scope.total);
};
This is the current structure of the database:
{
"players" : [ {
"R" : 0,
"Team" : "Industry",
"Y" : 0,
"assists" : 0,
...
}],
"users" : {
"l3J1TVsFNLMi0Oxg6hz4AJpacE53" : {
"email" : "example@email.com",
"fullname" : "Djflex11",
"teamname" : "deji awoniyi",
...
}
}
}
My Challenge
The issue I'm facing is ensuring that a player cannot be selected twice by the same user. Currently, my code prevents a player from being selected twice locally, but allows the same player ID to be pushed to the Firebase database. My challenge is figuring out how to check the 'total' node so that if a selected player is already in the database, it will be removed instead of inserted again. I am aware that 'indexOf' should be avoided with Firebase.